LeetCode:Power of Two

Given an integer, write a function to determine if it is a power of two.

解题思路

1,最高位为1,其余都为0.位运算判断方法为num&(num-1)
2.循环

code

1
2
3
4
5
6
7
bool isPowerOfTwo(int n) {
if(n <= 0) return false;
while(n%2 == 0) {
n /= 2;
}
return 1 == n;
}
1
2
3
4
5
6
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && 0 == (n & (n-1));
}
};