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;
}
本文介绍了一种高效的方法来计算一个无符号整数中二进制表示形式下1的个数(即汉明重量)。通过使用位操作,特别是按位与运算符,可以在O(k)的时间复杂度内完成此操作,其中k为二进制1的个数。
555

被折叠的 条评论
为什么被折叠?



