Problem 483
Counting Bits
Easy · 10 pts · Dynamic Programming, Bit Manipulation
Problem
For every integer i from 0 to N, count the number of 1 bits in its binary representation, and print all N + 1 counts. Counting each number separately is O(N log N); the recurrence bits[i] = bits[i >> 1] + (i & 1) reuses earlier answers and runs in O(N).
Input
A single integer N.
Output
Print N + 1 counts for 0, 1, ..., N, separated by spaces.
Constraints
0 <= N <= 100000
Example input
5
Example output
0 1 1 2 1 2
Explanation
0 to 5 in binary are 0, 1, 10, 11, 100 and 101, which contain 0, 1, 1, 2, 1 and 2 one-bits.