您的位置:首页 > 其它

[LeetCode] Power of Two

2015-07-12 15:46 711 查看
Given an integer, write a function to determine if it is a power of two.

判断一个数是不是2的幂。

思路,找出该数中二进制位1的个数

时间复杂度:O(n)

代码:

public boolean isPowerOfTwo(int n) {
if(n<1)
return false;
int cnt=0;
while(n>=1)
{
if((n&0x0001) == 1)cnt++;
n=n>>1;
}
return cnt==1;
}


优化:

return   n&(n-1)==0;


扩展:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: