您的位置:首页 > 其它

LeetCode 191. Number of 1 Bits (Easy)

2017-11-15 13:15 387 查看

题目描述:

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

Example:

The 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.


题目大意:找出一个无符号整数的二进制形式的1的个数。

思路:直接做也不是不可以(循环找1)。但是我从网上看到了一个很巧妙的方法:当n不等于0时,n = n & (n - 1),循环次数就是1的个数。思考了一下:n & n - 1可以令最低位的1消掉,所以每一次消除一个最低位的1,消除的次数就是1的个数了。

以题目为例:

nn-1n & n - 1
000000000000000000000000000010110000000000000000000000000000101000000000000000000000000000001010
000000000000000000000000000010100000000000000000000000000000100100000000000000000000000000001000
000000000000000000000000000010000000000000000000000000000000011100000000000000000000000000000000
c++代码:

class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while (n)
{
n = n & (n - 1);
ans++;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: