AceYourInterviews
Checking sign-in…

148. Counting Bits

StarterBinary-parent population-count recurrence in increasing value order

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.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Even and odd values share a binary parent

5
[0,1,1,2,1,2]