Question - Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
int hammingWeight(uint32_t n) {
int count = 0;
while(n>0){
count+=n&1;
n>>=1;
}
return count;
}
Can you come up with a better method?
One gentleman came up with this
int hammingWeight(uint32_t n) {
int count = 0;
while (n) {
n &= (n - 1);
count++;
}
return count;
}
How does one come up with such creative solutions?
And do you have a better one or any improvements I can make to my solution?