Given an integer, write a function to determine if it is a power of two.
AC代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
int count=0;
for(int i=0;i<sizeof(int)*8;i++){
if(n>>i&1==1)
count++;
if(count>=2)
return false;
}
return true;
}
};
看了大牛的解答,后自愧不如,代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n&(n-1));
}
};