1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
    // 判断是否是 2 的幂次
    public static boolean isPowerOfTwo(int num) {
        return (num & num - 1) == 0;
    }

    // 测试用例
    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            if (isPowerOfTwo(i)) {
                System.out.println(String.format("dec: [%s], bin: [0b%s].", i, Integer.toBinaryString(i)));
            }
        }
        // dec: [0], bin: [0b0].
        // dec: [1], bin: [0b1].
        // dec: [2], bin: [0b10].
        // dec: [4], bin: [0b100].
        // dec: [8], bin: [0b1000].
        // dec: [16], bin: [0b10000].
        // dec: [32], bin: [0b100000].
        // dec: [64], bin: [0b1000000].
    }