类似的题解详见:
leetcode_326. Power of Three分析
leetcode_342. Power of Four分析
题目链接
【题目】
Given an integer, write a function to determine if it is a power of two.
【分析】
解法1:
令temp=1,然后temp *= 2, 判断temp == n ?
class Solution {
public:
bool isPowerOfTwo(int n) {
if( n <= 0 ) return false;
if( n == 1 ) return true;
if( n % 2 == 1 ) return false;
long temp = 1;
while( temp <= n ){
if( temp == n ) return true;
temp *= 2;
}
return false;
}
};
解法2:
不断n /= 2, 判断n == 1 ?
class Solution {
public:
bool isPowerOfTwo(int n) {
if( n <= 0 ) return false;
if( n == 1) return true;
if(n%2 == 1) return false;
while(n>1){
if(n%2 == 1){
return false;
}
n = n/2;
}
return true;
}
};
解法3:
二进制位移
1 2 4 8 16 ….整数
1 10 100 1000 10000 ….二进制
发现只是最高位为1,其他为0,可以不断右移,计算1的个数和==1?
class Solution {
public:
bool isPowerOfTwo(int n) {
int count = 0;
while (n > 0) {
count += (n & 1);
n >>= 1;
}
return count == 1;
}
};
解法4:
二进制位特征
比如16
16:10000
(16-1):1111
16&(16-1)=0
所以特征:n & ( n - 1 ) == 0?
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && ( n & ( n - 1 ) ) == 0;
}
};