AlgoViz
← All problems

Count Set Bits (Hamming Weight)

Easy+70 XPteaches: Bits & Binary

Given a non-negative integer `n`, return the number of `1` bits it has in binary (its 'Hamming weight'). Example: 13 is `1101`, which has three `1` bits.

Example: n = 13 (1101) → 3

Check every bit: Inspect each of the fixed-width bits; add 1 for every bit that's set. (time O(k), space O(1))

No visualization loaded.

Watch

i

Press Run to begin.

Why the best approach wins

Checking every bit always does a fixed number of steps (one per bit width). The n & (n−1) trick instead loops only ONCE per bit that is actually set — for a number with few 1s, that's far fewer iterations, while never touching the zero bits at all.

Check every bit: O(k) time / O(1) spaceClear the lowest set bit: O(s) time / O(1) space

Your turn — implement hammingWeight

Loading editor…