Given a non-negative integer, return the number of 1 bits in its binary representation - its Hamming weight.
We use analytics and advertising cookies to understand how the site is used and whether our ads on Facebook and Instagram work. They are set only if you accept. See our Privacy Policy for details.
Given a non-negative integer, return the number of 1 bits in its binary representation - its Hamming weight.
An easy bit manipulation problem, graded against 6 test cases (3 of them hidden).
XOR, masks, and shifts - constant-space tricks for counting and pairing.
Reach for it when you see: "Appears once/twice", powers of two, or an explicit O(1) space requirement.
More Bit Manipulation problems →The baseline solution shifts right 32 times, testing the low bit each round. Correct, and always exactly 32 iterations regardless of the input.
Brian Kernighan's trick does better. Subtracting 1 flips the lowest set bit to 0 and turns every zero below it into a 1; ANDing with the original therefore clears exactly that lowest set bit and preserves everything above. Repeating until the value is zero runs once per set bit, so a number with three 1s takes three iterations rather than 32.
Worked example: `12` is `1100`. `12 & 11` is `1100 & 1011` = `1000`, and `8 & 7` is `1000 & 0111` = `0`. Two iterations, two set bits.
The same identity is the basis of the classic `n & (n - 1) === 0` test for powers of two - a number with exactly one set bit becomes zero after one clear.
One JavaScript caveat: bitwise operators coerce to signed 32-bit, so values at or above 2^31 need `>>> 0` or a comparison against `0` written carefully. Python's unbounded integers have no such issue.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.