1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    /** 计算大于 n 的最近的 2 的幂次的数 */
    public static int method1(int n) {
        int newCapacity = n;
        newCapacity |= newCapacity >>>  1;
        newCapacity |= newCapacity >>>  2;
        newCapacity |= newCapacity >>>  4;
        newCapacity |= newCapacity >>>  8;
        newCapacity |= newCapacity >>> 16;
        newCapacity ++;
        return newCapacity;
    }

    /** 计算大于等于 n 的最近的 2 的幂次的数 */
    public static int method2(int n) {
        int newCapacity = n - 1;
        newCapacity |= newCapacity >>>  1;
        newCapacity |= newCapacity >>>  2;
        newCapacity |= newCapacity >>>  4;
        newCapacity |= newCapacity >>>  8;
        newCapacity |= newCapacity >>> 16;
        newCapacity ++;
        return newCapacity;
    }

    // 以下是测试代码
    public static void main(String[] args) {
        System.out.println(method1(15)); // 16
        System.out.println(method1(16)); // 32
        System.out.println(method1(17)); // 32

        System.out.println(method1(15)); // 16
        System.out.println(method1(16)); // 16
        System.out.println(method1(17)); // 32
    }