Counting Bits
easy
bit-manipulation
dynamic-programming
Given a non-negative integer n, return an array answer where answer[i] is the number of 1 bits in the binary representation of i for every 0 <= i <= n.
Input / output
- Input:
n: int - Output:
int[]of lengthn + 1
Examples
n = 2returns[0,1,1].0has zero set bits,1has one, and2(10in binary) also has one.n = 5returns[0,1,1,2,1,2].3is11and5is101, so both contribute two set bits.n = 0returns[0]. The range still includes zero itself.
Constraints
0 <= n <= 10^5
Edge cases
ncan be zero.- The answer must include every value from
0throughnin order.
Target complexity
- Aim for
O(n)time andO(n)output space.
Hints
i >> 1drops the least significant bit ofi.- The bit count of
iequals the bit count ofi >> 1plus the final biti & 1.
Follow-up
Can you derive the same recurrence using i & (i - 1) instead?
Examples
Example 1
Input: n = 2
Output: [0,1,1]
Example 2
Input: n = 5
Output: [0,1,1,2,1,2]
Example 3
Input: n = 0
Output: [0]
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.