Counting Bits
Easy
Bit ManipulationDynamic Programming
Problem
Given an integer n, return an array ans of length n+1 where ans[i] is the number of 1-bits in i's binary representation.
Example 1
Input: n = 2
Output: [0,1,1]
Example 2
Input: n = 5
Output: [0,1,1,2,1,2]
Constraints
- 0 ≤ n ≤ 10⁵
Approach — Dynamic Programming
This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) to O(n²) time.
Solution code
Java
class Solution {
public int[] countBits(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) dp[i] = dp[i >> 1] + (i & 1);
return dp;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Counting Bits interactively → ← All solutions