https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
以下几种方法均(8ms)
1、可以发现2的幂只有最高位是1,故n&(n-1)== 0
class Solution {
public:bool isPowerOfTwo(int n) {
if(n<=0)
return false;
return !(n&(n-1));
}
};
2、一直整除2,最后为1,且无余数
class Solution {
public:
bool isPowerOfTwo(int n) {
while(n != 0 && n%2 == 0){
n >>= 1;
}
if(n == 1)
return true;
return false;
}
};
3、统计二进制中1的个数是否为1
class Solution {
public:
bool isPowerOfTwo(int n) {
int sums = 0;
while(n/2!=0){
sums += n%2;
n /= 2;
}
sums += n%2;
return sums==1;
}
};
4、利用2^32 = 4294967296
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n>0 && 4294967296%n == 0);
}
};
5、递归
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n <= 0)
return false;
if(n==1||n==2)
return true;
return n%2 == 0 && isPowerOfTwo(n/2);
}
};