问题描述:
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
示例:
the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
问题分析:
可根据向右移位与1按位与操作,可得‘1’的数目。
还有一种更高效的方式 : n = n &( n -1 )
过程详见代码:
按位与
class Solution {
public:
int hammingWeight(uint32_t n) {
uint32_t flag = 1;
int res = 0;
while(n)
{
res += (n & flag);
n = n >> 1;
}
return res;
}
};
更高效方式:
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}