Number of 1 bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
求给定无符号数中1的出现次数,比如11的二进制00000000000000000000000000001011
中包含3个1,则返回3
这道题用Java解需要非常小心,因为Java没有无符号int
如果是C语言的话可以循环n>0
然后不断右移n并且判断最低位&1==1
来给计数器加一。
Java中需要一些技巧。n & (n-1)
可以用来消除最低位上的1,由此我们来判断计数器是否加一。
public int hammingWeight(int n) {
if (n == 0) return 0;
int result = 0;
while (n != 0) {
n&=(n-1);
result++;
}
return result;
}