◀ THE GRIND — BIT MANIPULATION

Number of 1 Bits

The drill: Count how many bits are set to 1 in a 32-bit integer — the classic warm-up for every bit trick that follows.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A 32-bit integer arrives, and the task is to count how many of its bits are set to 1 in its binary representation.

The value is treated as a fixed-width 32-bit pattern rather than a mathematical integer that could grow arbitrarily large, so the count only ever ranges from zero, for an all-zero pattern, up to 32, for a pattern of all ones.

The result is that single count — an integer between 0 and 32 — with no need to report which positions held the 1 bits, only how many there were.

EX 01
n = 0
0
NO BITS SET
EX 02
n = 1
1
SINGLE LOWEST BIT
EX 03
n = 2
1
SINGLE BIT, NOT THE LOWEST
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Checking whether a value is odd tells you its lowest bit; shifting right walks that check across every position. What's the ceiling on how many shifts you'd ever need?

HINT 2 THE STRUCTURE

A fixed 32 checks always works, but most of that work is wasted once the remaining bits are all zero. Is there a move that skips straight past the zero stretches?

HINT 3 ONE STEP FROM THE ANSWER

n & (n − 1) always clears exactly the lowest set bit. Loop that operation and count iterations until n hits zero — you touch each 1-bit once, nothing else.

COACH'S BOARD — THE PATTERN, STEP BY STEP
KERNIGHAN'S DROPPATTERN · KERNIGHAN'S TRICKn = 7 (0111)
0
1
1
1
BITS CLEARED
count0
STEP 1

7 in binary is 0111. n & (n − 1) always drops the lowest set bit — count how many drops it takes to reach zero.

STEP 1 / 5 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/number-of-1-bits.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        while n:
            n &= n - 1  # clear the lowest set bit
            count += 1
        return count
TIME O(K) FOR K SET BITSSPACE O(1)PYTHON · RACE PACE · 7 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED