Given an integer n, return an array ans of length n+1 such that for each i (0 ≤ i ≤ n), ans[i] is the number of 1's in the binary representation of i.
n = 2[0,1,1]n = 5[0,1,1,2,1,2]Every number i can be formed by taking i>>1 (dropping the last bit) and optionally adding 1 (the last bit i&1). Since i>>1 < i, dp[i>>1] is always already computed. This gives us a perfect O(1) recurrence per element — no counting, no loops, just table lookups.
Counting the bits of each number separately takes O(n log n). But each count can be built from a smaller number.
Shifting i right by one drops its last bit. So i has the same bits as i shifted right, plus its last bit. That gives the rule: bits of i equals bits of i over 2, plus i AND 1. Because i over 2 is smaller, its count is already in the array.
I shifted right is i without its last bit. Dynamic programming over smaller numbers.
Run the animation above on your own input, or watch the 1:28 video explanation of Counting Bits with a dry run and Java code.