Back to DSA
Counting Bits
easyGiven a non-negative integer n, produce an array of length n + 1 in which the value at index i equals the number of 1-bits in the binary representation of i.
Examples
Example 1:
Input:
n = 3Output:
[0,1,1,2] Example 2:
Input:
n = 7Output:
[0,1,1,2,1,2,2,3]Hints
class Solution {
public int[] countBits(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) dp[i] = dp[i >> 1] + (i & 1);
return dp;
}
}Time complexity
O(n)Space complexity
O(n)