Number of 1 Bits
Count set bits in an unsigned integer.
Why does this pattern fit?
Restate the exact job
Count set bits in an unsigned integer.
n & (n−1) removes the lowest set bit.
O(number of set bits) time · O(1) space
Signed shifts can preserve the sign bit indefinitely in some languages.
How to solve Number of 1 Bits
The goal is to solve this problem from the pattern, not to memorize a finished answer. Use this as a check after your own attempt.
What the question asks
Count set bits in an unsigned integer.
Why Bit manipulation fits
n & (n−1) removes the lowest set bit.
State to maintain
The integer and a counter.
Transition
Repeatedly clear one set bit and increment until n is zero.
Time and space
O(number of set bits) time · O(1) space
Counterexample to the tempting mistake
Signed shifts can preserve the sign bit indefinitely in some languages.
Prove it again tomorrow
Close this page. Rebuild the state and transition from memory, write a test that exposes the mistake above, then solve a fresh input without looking back. A same-day reread is practice, not proof of retention.