From : 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.
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while(n) {
count += n&1;
n >>= 1;
}
return count;
}
};
Better Solution:
This is based on bit-manipulation, referenced by Dora' notes.
class Solution {
public:
int hammingWeight(uint32_t n) {
n = ((0xAAAAAAAA&n)>>1)+(0x55555555&n);
n = ((0xCCCCCCCC&n)>>2)+(0x33333333&n);
n = ((0xF0F0F0F0&n)>>4)+(0x0F0F0F0F&n);
n = ((0xFF00FF00&n)>>8)+(0x00FF00FF&n);
n = ((0xFFFF0000&n)>>16)+(0x0000FFFF&n);
return n;
}
};
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
n = ((n & 0xAAAAAAAA) >>> 1) + (n & 0x55555555);
n = ((n & 0xCCCCCCCC) >>> 2) + (n & 0x33333333);
n = ((n & 0xF0F0F0F0) >>> 4) + (n & 0x0F0F0F0F);
n = ((n & 0xFF00FF00) >>> 8) + (n & 0x00FF00FF);
n = ((n & 0xFFFF0000) >>> 16) + (n & 0x0000FFFF);
return n;
}
}