Number of 1 Bits 二进制中1的个数
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
考虑:这题的巧妙之处是能够想到n&(n-1)可以去掉n二进制末尾的1,例如7的二进制为111,(7-1)的二进制为110,111&110=110。如此循环,当n为0时便可得出1的个数。
public int hammingWeight(int n) {
int count = 0;
while(n!=0){
count++;
n = n & (n-1);
}
return count;
}