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)));
}
};