progress

~/problems / Bit manipulation

Counting Bits

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

easy ~15 min

Write ones_table(n: int) -> list[int]: a list of length n + 1 where table[i] is the number of 1 digits in the binary form of i.

ones_table(3)   # [0, 1, 1, 2]
ones_table(6)   # [0, 1, 1, 2, 1, 2, 2]
ones_table(0)   # [0]

0 <= n <= 10^6.

⭐ Bonus: a speed test with n = 1,000,000 earns a star in O(n) total, constant work per entry. Counting each number's digits from scratch is O(n log n).

Show hint

every i > 0 is a smaller number with one binary digit added at the end, or with one 1 removed. Its entry is already in the table; adjust by 0 or 1.

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