小于0的不是2的幂
大于零的,如果对应的二进制只有1个1,就是属于2的幂
public class Test231 {
@Test
public void test() {
System.out.println(hammingWeight(16));
}
public boolean isPowerOfTwo(int n) {
return n < 0 ? false : hammingWeight(n);
}
public boolean hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; i++) {
if ((n & 1) == 1) {
count++;
}
n = n >> 1;
}
return count == 1;
}
}