PROBLEM 71 OF 75

Number of 1 Bits

Count set bits in an unsigned integer.

PATTERNBit manipulationWrite the bit truth table before the code.
SPOT THE SIGNAL

Why does this pattern fit?

FRAME · 1 OF 4

Restate the exact job

Count set bits in an unsigned integer.

WHY THIS FITS

n & (n−1) removes the lowest set bit.

COMPLEXITY

O(number of set bits) time · O(1) space

COMMON FAILURE

Signed shifts can preserve the sign bit indefinitely in some languages.

THE REASONING, IN ONE PLACE

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.

Open blank recall ↗