Pop Count for Each Number
Intuition
The most direct approach is to compute the number of set bits for each integer from 0 to n individually. For each number, we can use Brian Kernighan's trick (i & (i - 1) removes the lowest set bit) to count bits efficiently. While this approach is straightforward, it does not leverage the relationship between numbers, so it does redundant work across iterations.
Algorithm
- Create a result array of size `n + 1`.
- For each integer `i` from `0` to `n`, count the number of set bits using a loop with `i & (i - 1)`.
- Store the count in `result[i]`.
- Return the result array.
O(n * k) where k is the average number of set bits per numberSpaceO(n) for the output arrayCode (C++ · Java · Python · Go)
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1);
for (int i = 0; i <= n; i++) {
int count = 0;
int x = i;
while (x != 0) {
x &= (x - 1);
count++;
}
ans[i] = count;
}
return ans;
}
};class Solution {
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 0; i <= n; i++) {
int count = 0;
int x = i;
while (x != 0) {
x &= (x - 1);
count++;
}
ans[i] = count;
}
return ans;
}
}from typing import List
class Solution:
def countBits(self, n: int) -> List[int]:
ans = [0] * (n + 1)
for i in range(n + 1):
count = 0
x = i
while x:
x &= x - 1
count += 1
ans[i] = count
return ansfunc countBits(n int) []int {
ans := make([]int, n+1)
for i := 0; i <= n; i++ {
count := 0
x := i
for x != 0 {
x &= x - 1
count++
}
ans[i] = count
}
return ans
}