https://leetcode.com/problems/power-of-two/description/
题目描述:Given an integer, write a function to determine if it is a power of two.
思路一: 位运算与1相与,如果结果为1则为2的幂次方
public boolean isPowerOfTwo(int n) {
if(n<=0)return false;
int count = 0;
while(n>0){
if((n&1)==1){
count++;
}
n=n>>1;
}
return count==1?true:false;
}
思路二:将该整数一直除2,直到小于2,如果结果为1则表示是2的幂次方
public class Solution{
public boolean isPowerOfTwo(int n){
double n_d = (double)n;
//将整形转为双精度型,并一直除以二直到小于2
while(n_d>=2){
n_d=n_d/2;
}
//结果为1则表示是2的幂次方
return n_d == 1.0;
}
}