Counting Bits

EasyBit manipulation

Count the 1 bits of every whole number from 0 to n, and return the counts as an array, the count for 0 first.

Aim for O(n) time, without counting each number’s bits from scratch.

Examples

Example 1
Input:  n = 6
Output: [0, 1, 1, 2, 1, 2, 2]

6 is 110 in binary, so the last entry is 2; 3 is 11, so its entry is 2 as well.

Example 2
Input:  n = 0
Output: [0]

Only the number 0, which has no 1 bits.

Constraints

  • 0 ≤ n ≤ 10⁵

Stuck?

Hint 1

i >> 1 is i with its lowest bit dropped, and it is smaller than i, so its count is already in your array.

Hint 2

The count for i is the count for i >> 1, plus 1 if i is odd (i & 1).

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur