题目
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.
分析与思路
方法一
采用最直接的办法,依次移位并与 0x1 做与操作。
代码:
int hammingWeight(uint32_t n) {
int cnt=0;
while(n)
{
if((n&0x1) == 1)
cnt++;
n=n>>1;
}
return cnt;
}
方法二
按照题目给出的提示的办法,hamming weight算法。在
Hamming Weight算法分析中有详细的分析。
代码:
class Solution {
public:
int hammingWeight(uint32_t x) {
const uint32_t m1 = 0x55555555; //binary: 0101...
const uint32_t m2 = 0x33333333; //binary: 00110011..
const uint32_t m4 = 0x0f0f0f0f; //binary: 4 zeros, 4 ones ...
const uint32_t h01 = 0x01010101; //the sum of 256 to the power of 0,1,2,3...
x -= (x >> 1) & m1; //put count of each 2 bits into those 2 bits
x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits
x = (x + (x >> 4)) & m4; //put count of each 8 bits into those 8 bits
return (x * h01)>>56; //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ...
}
};