Count the 1 Bits
You get a non-negative integer n. Think of it as a 32-bit unsigned number.
Return how many bits of n are 1 in its binary form.
Note for JavaScript
JavaScript bitwise operators (&, |, ^, <<, >>) work on 32-bit signed integers. A value of 2^31 or more becomes negative under them. Use the unsigned right shift >>> to move bits to the right, and x >>> 0 to turn a result back into an unsigned number.
Hint
Look at the lowest bit with n & 1, then shift n one place to the right. Repeat until n is 0. A faster way: n & (n - 1) removes the lowest 1 bit, so you can count how many times you can do that.
Examples
Example 1
- Input:
- 44
- Output:
- 3
44 in binary is 101100. It has three 1 bits.
Example 2
- Input:
- 2147483648
- Output:
- 1
2147483648 is 2^31. In binary it is a 1 followed by 31 zeros, so only one bit is 1.
Example 3
- Input:
- 4294967295
- Output:
- 32
4294967295 is 2^32 - 1. All 32 bits are 1.
Constraints
0 <= n <= 2^32 - 1(that is,4294967295)
Run checks your code against the 3 examples. Submit checks it against all 203 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.