Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
bool isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
/* 计算最低位1的个数 */
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
起初理解错了题目,算成了是否是2的倍数,其实是power,这样就简单多了。
也可以这样:
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (!(n & (n - 1)));
}
};