题目描述:
Given an integer, write a function to determine if it is a power of two.
看一个数是不是2的完全平方数。
对于这种玩数字的题,我们应该首先考虑位操作 Bit Operation。
如果一个数是2的完全平方数,那么最高位为1,其他位为0.
一种方法是检查每一位,如果为1就将cnt+1,最后判断cnt是否为1即可
代码如下:
public class Solution {
public boolean isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
}
还有一个简单方法:
public class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && ((n & (n - 1)) == 0 );
}
}