Skip to content
Rain Hu's Workspace
Go back

[Java] Integer.bitCount 解析

Rain Hu

Integer.bitCount 的函式解析

雛形

public static int bitCount(int i){
    int count = 0;
    while (i > 0) {
        if ((i & 1) == 1)    // 如果最低位為 1,count就加 1
            count++;
        i >>= 1;             // 向右推進 1 位,等同於 num /= 2;
    }
    return count;
}

優化

public static bitCount(int i){
    int count = 0;
    while (i > 0){
        i = i & (i - 1);       // 0b0101_1100 - 1 = 0b0101_1011, 且 0b0101_1100 & 0b0101_1011 = 0b0101_1000;
        count++;
    }
    return count;
}

利用 int 的特性再優化

private static int bitCount(int i){
    i = (i & 0x55555555) + ((i >>> 1) & 0x55555555);  // 0b0101_0101_0101_0101_0101_0101_0101_0101
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);  // 0b0011_0011_0011_0011_0011_0011_0011_0011
    i = (i & 0x0f0f0f0f) + ((i >>> 4) & 0x0f0f0f0f);  // 0b0000_1111_0000_1111_0000_1111_0000_1111
    i = (i & 0x00ff00ff) + ((i >>> 8) & 0x00ff00ff);  // 0b0000_0000_1111_1111_0000_0000_1111_1111
    i = (i & 0x0000ffff) + ((i >>>16) & 0x0000ffff);  // 0b0000_0000_0000_0000_1111_1111_1111_1111
    return i;
}

Source Code(final)

public static int bitCount(int i) {
    // HD, Figure 5-2
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    i = i + (i >>> 8);
    i = i + (i >>> 16);
    return i & 0x3f;
}

Share this post on:

Previous
[C++] How to Initialize vector in C++
Next
[OS] Lec 1 - Introduction