InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Number of 1 Bits

easy Original ↗ 00:00

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 Check each bit position: use `n & 1` to read the lowest bit and `n >>= 1` to move to the next. Count the `1`s.
Hint 2 There is a way to skip 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug