计算一个无符号整数的二进制表示中1的个数,这个问题又被称作[url=http://en.wikipedia.org/wiki/Hamming_weight]Hamming weight[/url]
Java中有支持的API:
Integer.bitCount
Long.bitCount
http://stackoverflow.com/questions/1458314/number-of-1s-in-32-bit-number
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20%28Ones%20Count%29
Java中有支持的API:
Integer.bitCount
Long.bitCount
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;
}
http://stackoverflow.com/questions/1458314/number-of-1s-in-32-bit-number
http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
http://aggregate.ee.engr.uky.edu/MAGIC/#Population%20Count%20%28Ones%20Count%29