Given an integer, write a function to determine if it is a power of two.
这道题看似很简单,也确实简单,只要一直除2,然后判断是否是2的幂次方。
但是这样速度势必不快,我是这样做的
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n == 0) return false;
if (n == 1) return true;
int base = 2;
int temp = n;
while (n % 2 == 0) {
if (n % base == 0) {
n = n / base;
base *= base;
} else {
base = 2;
}
}
if (n == 1) return true;
return false;
}
};
后来看了discuss里面的一个方法,只能自己思维太不灵敏了。。
主要想法是利用Value&(Value-1)按位与,稍微想想就知道,这个是求数二进制情况下,末尾有多少个连续的0
bool isPowerOfTwo(int n) {
if(n<=0) return false;
if(n&(n-1)) return false;
return true;