progress

~/problems / Bit manipulation

Number of 1 Bits

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~10 min

A control panel has up to 63 switches, stored as one non-negative integer: switch i is on when the binary digit worth 2^i is 1.

Write count_on(state: int) -> int: how many 1 digits state has in binary.

count_on(13)          # 3   (13 is 1101 in binary)
count_on(0)           # 0
count_on(256)         # 1   (100000000)
count_on(2**63 - 1)   # 63

0 <= state <= 2^63 - 1. Use integer operations only (no strings), and aim for a loop that runs once per 1, not once per digit.

Show hint

compare state with state - 1 in binary: the lowest 1 and everything after it flip. Combining the two removes exactly one 1 per step.

Topic: Bit manipulation (IP / CIDR). IPv4 as a 32-bit int; lowest set bit for block sizes.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc