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 = 4
Output: [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 000 to nnn, we can find that for a binary number 1B1B1B (BBB can be any binary sequence), the number of 1 in BBB is computed and 1B1B1B has one more 1 compared with BBB. Thus, we can do a dynamic programming, transferring the number of 1 from BBB to 1B1B1B.
Code
class Solution:
def countBits(self, n: int) -> List[int]:
power = 1
dp = [0]*(n+1)
dp[0] = 0
for i in range(1, n+1):
if i == power*2:
power *= 2
dp[i] = dp[i-power]+1
return dp