1. 题目
2. 思路
(1) Integer.bitCount()
- 2的幂次方的二进制位中只有1个1,调用Integer.bitCount()统计1的个数。
(2) 位运算
(3) 取余
3. 代码
public class Test {
public static void main(String[] args) {
System.out.println(Integer.toBinaryString(-2147483646));
}
}
class Solution {
public boolean isPowerOfTwo(int n) {
return n > 0 && Integer.bitCount(n) == 1;
}
}
class Solution1 {
public boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}
class Solution2 {
public boolean isPowerOfTwo(int n) {
return n > 0 && (1 << 30) % n == 0;
}
}