Menu
CoddyTech

Counting Bits

Given a whole number n that is 0 or more, return an array of n+1 entries where entry i is the number of 1s in the binary form of i, for every i from 0 to n.

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: no 1s, then one, then one.
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 #1

Test #2

Argument

n = 2

Expected Output

[0, 1, 1]