https://leetcode.com/problems/number-of-1-bits/
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.
int hammingWeight(uint32_t n)
{
int res = 0;
while (n > 0)
{
if (n & 1 == 1)
res++;
n >>= 1;
}
return res;
}
方法2
同样是位操作,利用n&(n-1)的操作:把n的最低位1置0。这个技巧在题231.Power of Two 也用到了
int hammingWeight(uint32_t n)
{
int res = 0;
while (n > 0)
{
n &= (n - 1);
res++;
}
return res;
}