Question: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011
has a total of three '1' bits.
My Code
var hammingWeight = function(n) {
for (i=0; i<32; i++) {
var mask = 1;
var count = 0;
if ((mask & n) != 0 ) {
mask <<= 1;
count++;
}
return count;
}
};
Test Case:
00000000000000000000000000001011
00000000000000000000000010000000
11111111111111111111111111111101
Expected Output:
3
1
31
Output:
1
0
1
What did I do wrong with my code?