Skip to content
BytePatterns

Set Bits For Every Number

EasyBit Manipulation#bit-shifting#reuse-smaller-answer~20m

Problem

Given a non-negative whole number n, return a list whose entry at index i is the number of ones in the binary form of i, for every i from 0 up to n inclusive. Try to fill the whole list in a single pass without looping over the digits of each number.

Examples

Input:  n = 5
Output: [0, 1, 1, 2, 1, 2]
Why:    0, 1, 10, 11, 100, 101 in binary
Input:  n = 2
Output: [0, 1, 1]
Input:  n = 0
Output: [0]
Why:    edge case, the list still holds the entry for zero itself

Hints

0 / 3

Stuck on the idea rather than the code? Counting Set Bits covers it.