338. Counting Bits
Problem
For every i from 0 to n, count the 1 bits in i's binary form, and return the counts as a list.
Example: n = 5 → [0,1,1,2,1,2]
Constraints: follow-up: O(n) without a built-in popcount.
bits[i] = bits[i >> 1] + (i & 1) — drop the last bit, reuse the answer.
Complexity: O(n).
class Solution:
def countBits(self, n: int) -> List[int]:
bits = [0] * (n + 1)
for i in range(1, n + 1):
bits[i] = bits[i >> 1] + (i & 1)
return bits
assert Solution().countBits(5) == [0, 1, 1, 2, 1, 2]
assert Solution().countBits(0) == [0]
assert Solution().countBits(2) == [0, 1, 1]
class Solution {
public int[] countBits(int n) {
int[] bits = new int[n + 1];
for (int i = 1; i <= n; i++) bits[i] = bits[i >> 1] + (i & 1);
return bits;
}
}
func countBits(n int) []int {
bits := make([]int, n+1)
for i := 1; i <= n; i++ {
bits[i] = bits[i>>1] + i&1 // i's bits = (i/2)'s bits + the last bit
}
return bits
}