148. Counting Bits
For each integer in the inclusive range zero to n, count how many one bits appear in its ordinary binary representation. Place each count at the corresponding output index.
Zero has a bit count of zero, and the output has n+1 entries. The problem asks for the full table, not just the count for n.
Example 1
Input
n=2
Output
[0,1,1]
Explanation: Zero has no one bits; one and binary ten each have one.
Example 2
Input
n=5
Output
[0,1,1,2,1,2]
Explanation: Binary eleven has two; binary one hundred has one.
Example 3
Input
n=0
Output
[0]
Explanation: The inclusive range still contains zero.
Constraints
0 <= n <= 106
Hints
Hint 1
Write i as 2q+b with b either zero or one.
Hint 2
What happens to its binary digits when you shift right once?
Hint 3
Use the already computed count at i>>>1 and add its last bit i&1.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Even and odd values share a binary parent
5
[0,1,1,2,1,2]