CodingNodes / Bit Manipulation / Number of 1 Bits System design Space play · ←→ step · R restart

Problem

Given a 32-bit non-negative integer n, return how many of its bits are 1.

The original problem treats n as an unsigned 32-bit value. Here every example is shown as an ordinary non-negative int below 231, so Python, Java and C++ all agree on it; bit 31 is always 0.

Constraints

  • 0 ≤ n < 2^31 (n is shown as a non-negative int; its 32-bit form has bit 31 equal to 0)

Examples: pick one to animate

Solutions

TimeO(1) SpaceO(1)

Time: The loop always runs exactly 32 times, whatever n is.

Space: One counter and the loop index.

Look at the bits one by one. Shift n right by i and keep only the lowest bit with & 1: that is bit i. Add it to a counter, for all 32 positions.