Counting Bits
Real-world version: Lit Lamps Per Ticket IdThe statement here is our own: the same inputs, outputs and technique.
A queue display shows a ticket id in binary on a row of lamps: a lamp is lit for each 1 in the binary form of the id, and dark for each 0. Ids run from 0 up to n inclusive.
Report the lit lamp count for each id in turn, starting at id 0 and finishing at id n, so the reported list holds one more entry than n. Id 0 lights nothing.
Aim for a running time linear in n, without a fresh scan of the bits of every id.
Examples
Example 1
- Input
- n = 9
- Output
- [0, 1, 1, 2, 1, 2, 2, 3, 1, 2]
Ids 0 to 9 in binary are 0, 1, 10, 11, 100, 101, 110, 111, 1000 and 1001, so the lit lamp counts run 0, 1, 1, 2, 1, 2, 2, 3, 1, 2.
Example 2
- Input
- n = 13
- Output
- [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3]
The counts for ids 0 to 9 are unchanged, and ids 10 to 13 are 1010, 1011, 1100 and 1101, lighting 2, 3, 2 and 3 lamps.
Example 3
- Input
- n = 0
- Output
- [0]
Only id 0 exists and it lights no lamp, so the answer holds a single zero.
Constraints
- 0 <= n <= 10^5
- The returned array has n + 1 entries, and every entry is at most 17.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def count_bits(n: int) -> list[int]:public int[] countBits(int n)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 10 test cases: 10 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Minimum Operations to Reduce an Integer to 0Real-world version: Gauge Calibration PressesMedium
- Beautiful ArrangementReal-world version: Divisible Crate PlacementsMedium
- Partition to K Equal Sum SubsetsReal-world version: Dealing Counterweights Onto HoistsMedium
- Shopping OffersReal-world version: Cheapest Basket at the Fastener CounterMedium