题目描述:
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的个数了。
以题目为例:
n | n-1 | n & n - 1 |
---|---|---|
00000000000000000000000000001011 | 00000000000000000000000000001010 | 00000000000000000000000000001010 |
00000000000000000000000000001010 | 00000000000000000000000000001001 | 00000000000000000000000000001000 |
00000000000000000000000000001000 | 00000000000000000000000000000111 | 00000000000000000000000000000000 |
c++代码:
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans = 0;
while (n)
{
n = n & (n - 1);
ans++;
}
return ans;
}
};