Menu
CoddyTech

Counting Bits

You get a whole number n that is 0 or more. For every number i from 0 to n, count how many 1s appear when i is written in binary. Return the counts as an array of n+1 entries, where entry i is the count for the number i.

Function

countBits(n: integer) → integer-array
ninteger
the last number to count, 0 or more
Returnsinteger-array
an array of n+1 counts, where entry i is the number of 1 bits in i

Constraints

  • 0 ≤ n ≤ 2 × 104

Examples

Input
n = 2
Output
[0, 1, 1]
Explanation
In binary, 0 is 0, 1 is 1 and 2 is 10. That is no 1s, then one, then one.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Can you fill the whole array in O(n) time, without a built-in function that counts bits and without counting each number from scratch?

Reset code
def countBits(n):
    # Write code here
Test cases

Case 1

Case 2

Input

n = 2

Expected

[0, 1, 1]