您的位置:首页 > 理论基础 > 数据结构算法

LeetCode 191. Number of 1 Bits

2018-03-17 00:41 423 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息