CodingNodes / Bit Manipulation / Counting Bits System design Space play · ←→ step · R restart

Problem

Given a non-negative integer n, build an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i, for every i from 0 to n.

Try to do it in one pass over 0..n, without counting the bits of each number from scratch.

Constraints

  • 0 ≤ n ≤ 100000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each number from 1 to n is filled with one table lookup and one addition.

Space: The answer array has n + 1 entries, which we must return anyway; nothing else grows.

Shifting a number right by one drops its lowest bit and leaves a smaller number whose count is already known. So the count of i is the count of i >> 1, plus 1 if the dropped bit (i & 1) was a 1.