Counting Bits
Examples
Example 1:
Input: n = 4
Output: [0,1,1,2,1]
Explanation:
Example 1:
Input: n = 4
Output: [0,1,1,2,1]
Explanation:
Given an integer n, count the number of 1's in the binary representation of every number in the range [0, n].
Return an array output where output[i] is the number of 1's in the binary representation of i.
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
0 <= n <= 1000Use DP: dp[i] = dp[i >> 1] + (i & 1). The number of set bits in i equals the number in i // 2, plus one if i is odd.
Right shifting removes the least significant bit. If that bit was 1, we add one; otherwise we add zero. This produces the correct count for each number in order.
O(n)O(n)class Solution:
def countBits(self, n: int) -> List[int]:
dp = [0] * (n + 1)
for i in range(1, n + 1):
dp[i] = dp[i >> 1] + (i & 1)
return dp