题目
解法一(不断除2判奇偶)
class Solution {
public:
bool res = false;
//一直除以2,一旦中间某个环节除成了奇数,就返回,如果最后除到了1则得到结果true
void check(int a){
if(a==1){
res = true;
return;
}
if(a%2==0)
check(a/2);
else{
res = false;
return;
}
}
bool isPowerOfTwo(int n) {
if(!n)
return false;
check(n);
return res;
}
};
解法二:根据二进制存储的规律
根据二进制存储的规律,明显2的几次方在二进制位表示中,都是表示在第几位存在1,那么就回到了之前的汉明距离的题目了,不过这次不同的在于,只能存在一个1。也就是直接
x&(x-1)
必等于0,否则不止一个1.
class Solution {
public:
bool isPowerOfTwo(int n) {
//把小于0的全排除
if(n<=0)
return false;
return (n&(n-1))==0;
}
};