InterviewPrepKit

Home / Coding / Bit Manipulation

Number of 1 Bits

easy Original ↗
Solving tips
  • Brian Kernighan's trick: n &= n - 1 clears the lowest set bit, so the loop runs once per set bit instead of once per bit, skipping all zeros.
  • Count each clear until n becomes 0; this is O(s) where s is the number of set bits (<= 32), O(1) space, faster than scanning all bits for sparse inputs.
  • For the 'called many times' follow-up, a precomputed 256-entry byte popcount table answers each 32-bit word in four lookups.
  • Pitfalls: don't confuse n & (n-1) with n & 1; and for possibly-negative inputs in Python, mask with & 0xFFFFFFFF or the while loop may not terminate as expected.

Problem

Given an unsigned 32-bit integer n, return the number of 1 bits it contains (its Hamming weight / population count). For example, 11 in binary is 1011, which has three 1 bits.

Examples

  • 11 (00000000000000000000000000001011) → 3
  • 128 (00000000000000000000000010000000) → 1
  • 4294967293 (11111111111111111111111111111101) → 31

Constraints

  • The input is a 32-bit integer.

Follow-up: if this function is called many times, can you make each call cheaper than scanning all 32 bits?

Think about it first

Hint 1 The direct way: look at each bit position, using `n & 1` to read the lowest bit and `n >>= 1` to move to the next. Count the `1`s.
Hint 2 There is a trick that skips the zeros entirely. `n - 1` flips the lowest set bit to `0` and turns every bit below it into `1`. What does `n & (n - 1)` then do to that lowest set bit?
Hint 3 `n & (n - 1)` clears the lowest set bit and leaves everything else. Repeat it until `n` becomes `0`; the number of iterations is exactly the number of set bits — so you loop once per `1`, not once per bit.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.