Problem
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.
solution1
常规解法: 用模板,然后右移一位。
int hammingWeight(uint32_t n) {
int count = 0;
for(int i = 0; i < 32; i++)
{
if( n & 0x01 )
{
count++;
}
n = n >> 1;
}
return count;
}
可以优化成这样 count += n&1;
solution2
对数据取余,也就是检测最后一位是否为1,然后右移一位。
int hammingWeight(uint32_t n) {
int result = 0;
for(n) {
result += n%2;
n /= 2;
}
}
solution3
用n&n-1
将最后一位不为0的位置0,直到n值为0.
int hammingWeight(uint32_t n) {
int ret = 0;
while(n)
{
n&=n-1;
++ret;
}
return ret;
}