Counting Bits
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.
Example 1:
Input: n = 4Output: [0,1,1,2,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
Constraints:
0 <= n <= 1000
Solution
If we go through the numbers from 0 0 0 to n n n, we can find that for a binary number 1 B 1B 1B ( B B B can be any binary sequence), the number of 1 in B B B is computed and 1 B 1B 1B has one more 1 compared with B B B. Thus, we can do a dynamic programming, transferring the number of 1 from B B B to 1 B 1B 1B.
Code
class Solution:def countBits(self, n: int) -> List[int]:power = 1dp = [0]*(n+1)dp[0] = 0for i in range(1, n+1):if i == power*2:power *= 2dp[i] = dp[i-power]+1return dp