Practice · Bit manipulation · 1 of 3

Count the 1 Bits up to n

Given an integer n, return a list of n + 1 numbers where item i is the number of 1 bits in the binary form of i, for every i from 0 to n.

For example, 5 is 101 in binary, so item 5 is 2. Counting each number's bits one at a time takes O(n log n) time; aim for O(n).

Example 1

Input
n = 2
Output
[0, 1, 1]
0 is 0, 1 is 1 and 2 is 10.

Example 2

Input
n = 6
Output
[0, 1, 1, 2, 1, 2, 2]
3 is 11, 5 is 101 and 6 is 110: two 1s each.

Constraints

  • 0 ≤ n ≤ 10⁴