Counting Bits
Easy · Bit manipulation
Jump to codeFor every integer from 0 through n inclusive, return its number of set bits. Assume n ≥ 0.
Examples
Example 1
n = 2
Output: [0,1,1]
Example 2
n = 5
Output: [0,1,1,2,1,2]
Constraints
- 0 <= n <= 1000
Need a hint?
Removing the last binary digit gives an already computed number.
Real bit manipulation interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Maximize the Bitwise AND of K Elements After Spending an Increment BudgetAmazon
- Implement IPv4 iterators and CIDR expansionOpenAI
- Implement firewall matching with CIDR rulesDatabricks
Solution approach
Initialize counts[0] = 0. For i from 1 to n, set counts[i] = counts[i >> 1] + (i & 1). The shift removes the last bit, and the mask contributes one exactly when that bit was set.
Complexity
O(n) time and O(n) output space.
Python reference solution
def countBits(n):
answer = [0] * (n + 1)
for value in range(1, n + 1):
answer[value] = answer[value >> 1] + (value & 1)
return answer
JavaScript solution
function countBits(n) {
const answer = Array(n + 1).fill(0);
for (let value = 1; value <= n; value++) answer[value] = answer[value >>> 1] + (value & 1);
return answer;
}
Java solution
import java.util.*;
class Solution {
public int[] countBits(int n) {
int[] answer = new int[n + 1];
for (int value = 1; value <= n; value++) answer[value] = answer[value >>> 1] + (value & 1);
return answer;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> countBits(int n) {
vector<int> answer(n + 1);
for (int value = 1; value <= n; value++) answer[value] = answer[value >> 1] + (value & 1);
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 6 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ 2 ]
[ 0, 1, 1 ]
[ 5 ]
[ 0, 1, 1, 2, 1, 2 ]
[ 0 ]
[ 0 ]
[ 1 ]
[ 0, 1 ]
[ 8 ]
[ 0, 1, 1, 2, 1, 2, 2, 3, 1 ]
Drafts are saved per language in this browser when storage is available.