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?
0 <= n <= 10^5, as per common constraint limits for LeetCode problems.1s?
One efficient way to solve this problem is by using dynamic programming and the properties of binary numbers:
1s in a binary number can be built from the number of 1s in smaller numbers.i in binary: if i is an even number, the number of 1s in i is the same as the number of 1s in i // 2 (shifting right by 1 bit).i is an odd number, it has one more 1 than i - 1.dp where dp[i] represents the count of 1s in the binary representation of i.dp[0] to 0 because the number 0 has no 1s.i from 1 to n, calculate dp[i] based on whether i is even or odd as explained above.def countBits(n: int) -> [int]:
# Initialize the array to store number of 1's for each integer
dp = [0] * (n + 1)
# Start from 1 and calculate number of 1's using previous numbers
for i in range(1, n + 1):
dp[i] = dp[i >> 1] + (i & 1)
return dp
dp is initialized with n+1 zeros since we need counts from 0 to n.1 to n.
i >> 1 is the integer division of i by 2, effectively shifting the bits to the right.i & 1 checks if the least significant bit of i is 1 (i.e., whether i is odd).dp[i] is calculated as the count of 1s in i >> 1 plus i & 1.dp which contains the result.0 to n once.n + 1.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?