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,实在是妙!!