Blind 75 · #72 · Bit Manipulation

Counting Bits

EasyDP on bitsTime O(n)Space O(1) beyond the output

Counting Bits is an easy Bit Manipulation problem from the Blind 75. The key pattern is dp on bits, and a good solution runs in O(n) time.

Problem

For every integer from zero through n, return its number of set bits.

Examples

Example 1

Input

5

Output

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

Example 2

Input

4

Output

[0,1,1,2,1]

Example 3

Input

7

Output

[0,1,1,2,1,2,2,3]

Approach

The bit count of i equals the count of i >> 1 plus its lowest bit, so fill the answers in increasing order.

PatternDP on bits
TimeO(n)
SpaceO(1) beyond the output

Watch out for

The output has n + 1 entries, from 0 to n.

More Bit Manipulation problems