Given an integer, write a function to determine if it is a power of two.
class Solution {
public:
bool isPowerOfTwo(int n) {
while(n && n%2 == 0)
{
n /= 2;
}
return n == 1;
}
};
2的次方数都只有一个1,剩下的都是0,所以我们的解题思路就有了,我们只要每次判断最低位是否为1,然后向右移位,最后统计1的个数即可判断是否是2的次方数,代码如下:
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)));
}
};