Binary Counter Exhibit

Easybit manipulationAlso known as Counting Bits

A science museum has a wall of light bulbs that counts in binary. Each second it shows the next number: 0, then 1, then 10, then 11, then 100, and so on, with a lit bulb for every 1 bit.

The museum's electrician is planning the power supply. For a show that counts from 0 up to n, she wants to know how many bulbs are lit at each number.

Your task

Write litBulbs(n). Return a list of length n + 1 where position i holds the number of 1 bits in the binary form of i.

Aim for O(n) total time: work out each count from a count you already have, instead of examining every bit of every number.

litBulbs(n: int) → int[]

Examples

Example 1
Input
n = 5
Output
[0, 1, 1, 2, 1, 2]
Why

0 = 0, 1 = 1, 2 = 10, 3 = 11, 4 = 100, 5 = 101. Counting the 1s gives 0, 1, 1, 2, 1, 2.

Example 2
Input
n = 8
Output
[0, 1, 1, 2, 1, 2, 2, 3, 1]
Why

The count drops back to 1 at 4 and at 8. Each power of two lights one bulb, after a run where many bulbs were lit (7 = 111 has three).

Constraints

  • 0 ≤ n ≤ 100,000
Start with brute force

For each number from 0 to n, count its 1 bits one at a time: check the last bit, shift right, repeat until the number is 0.

Each number takes up to about 17 steps when n is 100,000, so this is O(n log n). It is not slow, but it throws away work: the count for 12 already contains the count for 6, which you computed a moment ago.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code