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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
method:
这一题比较简单,很容易想到位的偏移(主要是前天看源码,内存页的存取各种offset看到晕—。—)
<span style="font-size:18px;">int hammingWeight(uint32_t n) {
int j = 0;
int count = 0;
for (j; j< 32;j++)
{
if((1<<j)&n)
{
count++;
}
}
return count;
}</span>