Example 1
- Input
- n = 2
- Output
- [0, 1, 1]
0 has zero ones, 1 has one, and 2 (10 in binary) has one.
Build an array where entry i holds the number of 1 bits in the binary form of i, for every i from 0 up to n.
Given an integer n, return an array ans of length n + 1 where ans[i] counts the number of 1 bits in the binary form of i, for every i from 0 to n.
Counting each number from scratch repeats work, because smaller answers already reveal larger ones: stripping the lowest set bit, or halving the number, lands on a value already computed. Aim for one linear pass with no built-in bit counter.
0 has zero ones, 1 has one, and 2 (10 in binary) has one.
3 (11) has two ones, 4 (100) has one, and 5 (101) has two.
The range still includes zero. Its binary representation has no set bits, so the returned array has one entry rather than being empty.
Binary digits describe how many powers of two make a number; count only the digits equal to one. Example 1 needs answers for 0, 1 and 2: their binary forms 0, 1 and 10 contain 0, 1 and 1 ones. Counting each separately works, but removing the last digit of 2 leaves 1, whose answer is already available. The removed digit contributes either zero or one, so smaller answers can build the entire array.
Reveal Count Each Number: intuition, complexity, and code
4 (100) has the same count as 2 (10), and 5 (101) has one more. What operation turns one into the other?i & 1.dp[i] = dp[i >> 1] + (i & 1) left to right from dp[0] = 0, since the halved index is always already computed.n = 100000 still fills in one pass with no per-number inner loop.dp[i >> 1] + i & 1 without parentheses where the language parses it as (dp[i >> 1] + i) & 1.n instead of n + 1, dropping the entry for n itself.When answers for 0 to n build on each other, look for a one-step reduction — here halving — that turns earlier results into current ones.