Online store~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-338bit-manipulation
A warehouse shelf has a row of status lamps, and a scanner reads the lamps as a number. Each lamp that is lit adds a power of two, so the number is a binary pattern. The scanner reports every number from 0 to n over a day, one for each reading.
The maintenance team wants to know, for every number from 0 to n, how many lamps are lit. That is the number of 1s in the binary form of the number. A day can have up to 3,000,000 readings.
Write lamps_lit(n).
n is a whole number from 0 upwards.n + 1 counts. Entry i is the number of 1s in the binary form of i.Input: n = 5
Output: [0, 1, 1, 2, 1, 2]A number i is the number i >> 1, which drops the last bit, followed by that last bit. So the count of i is the count of i >> 1 plus the last bit, i & 1. The trace uses counts that are already known.
| i | Binary | i >> 1 |
Count of i >> 1 |
Last bit | Count of i |
|---|---|---|---|---|---|
| 1 | 1 | 0 | 0 | 1 | 1 |
| 2 | 10 | 1 | 1 | 0 | 1 |
| 3 | 11 | 1 | 1 | 1 | 2 |
| 4 | 100 | 2 | 1 | 0 | 1 |
| 5 | 101 | 2 | 1 | 1 | 2 |
Input: n = 0
Output: [0]The number 0 has no lit lamp.
Input: n = 8
Output: [0, 1, 1, 2, 1, 2, 2, 3, 1]The number 7 is 111, with three lit lamps. The number 8 is 1000, with one.
0 ≤ n ≤ 3,000,000Counting the bits of every number one by one costs up to 22 steps for each of 3,000,001 numbers, which is about 6 × 10^7 steps. It repeats work. Each count can be built from the count of a smaller number in one step, so the whole list costs about 3 × 10^6 steps.