您的位置:首页 > 其它

[LeetCode]Power of Two

2015-07-28 17:50 239 查看
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: