191. 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的个数
/* 二进制数借位会从最右边的1来借,如:
12 = 0000 1100, 12 - 1 = 11 = 0000 1001
0000 1100
& 0000 1001
= 0000 1000 = 8 (取掉了最右边的1)
同理:
8 = 0000 1000, 8 - 1 = 7 = 0000 0111
0000 1000
& 0000 0111
= 0000 0000 = 0
如此,我们便算出了12的二进制1的个数
*/
int hammingWeight(uint32_t n) {
int counter = 0;
while(n){
n &= (n - 1);
++counter;
}
return counter;
}