LeetCode 231 Power of Two
Given an integer, write a function to determine if it is a power of two.
DiffcultyEasy
Similar Problems
[LeetCode ] Number of 1 Bits Easy
[LeetCode ] Power of Three Easy
[LeetCode ] Power of Four Easy
Analysis
思路一 来观察下2的次方数的二进制写法的特点:
1 2 4 8 16 ....
1 10 100 1000 10000 ....
那么我们很容易看出来 2 的次方数都只有一个 1,剩下的都是 0,所以我们的解题思路就有了,我们只要每次判断最低位是否为 1,然后向右移位,最后统计 1 的个数即可判断是否是 2 的次方数
思路二 还有一个技巧,如果一个数是 2 的次方数的话,根据上面分析,那么它的二进数必然是最高位为 1,其它都为 0 ,那么如果此时我们减 1 的话,则最高位会降一位,其余为 0 的位现在都为变为 1 ,那么我们把两数相与,就会得到 0 ,用这个性质也能来解题,而且只需一行代码就可以搞定。
Solutions
解法一
class Solution {
public:
bool isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
};
解法二
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (!(n & (n - 1)));
}
};