Given a positive integer that fits in 32 bits, return the number of 1 bits in its binary representation (its population count, or Hamming weight).
Before you code
11 is 1011 in binary, so the answer is 3. The direct approach checks the lowest bit, shifts right and repeats: 32 steps at most. A neater trick clears one set bit per step, so it loops only as many times as there are 1s.
Hints
n & 1is the lowest bit.n >> 1shifts every bit one place right.n & (n - 1)clears the lowest set bit. Subtracting 1 flips the lowest 1 and every 0 below it, so the AND removes exactly that 1.- Most languages also have a built-in, such as
Integer.bitCountin Java orint.bit_count()in Python 3.10+. Write the loop first, then compare.
Production & complexity notes
When solving Number of 1 bits on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Bits, bytes and number representation to reinforce the underlying pattern.
What it practices
Reading an integer as the row of bits it really is, from Bits, bytes and number representation.