您的位置:首页 > 其它

leetcode[231]:Power of Two

2015-07-07 20:07 411 查看
Power of Two

Given an integer, write a function to determine if it is a power of two.

是2的整数次幂问题,很容易想到位操作。

看到了Discuss中某大神的做法,十分膜拜:

https://leetcode.com/discuss/44155/1-line-python-solution

转换成C语言如下:

bool isPowerOfTwo(int n) {
return (n>0) && (n & (n-1))==0;
}


前提: n>=0;

2的整数次幂换成二进制必然是1+x个0,n-1必然是x个1,n & n-1 必然全是0,实在是妙!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bit