Skip to content
DSA Patterns
Menu
Language
Bit ManipulationLC #1912 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Number of 1 Bits

Problem (restated)

Return the number of set bits (Hamming weight) in a 32-bit integer.

Intuition

n &= n-1 clears the lowest set bit; count until n=0.

Approaches

Brian Kernighan

Unverified
Time O(popcount)Space O(1)

Idea. while n: n&=n-1; c++.

Walkthrough. 11 → 3 (1011).

Trade-offs. n&1 + n>>>1 loop is O(32); Kernighan is O(#bits).

Solution
export function hammingWeight(n: number): number {
  let c = 0;
  n >>>= 0;
  while (n) {
    n &= n - 1;
    c++;
  }
  return c;
}
export function hammingWeight(n: number): number {
  let c = 0;
  n >>>= 0;
  while (n) {
    n &= n - 1;
    c++;
  }
  return c;
}

Template connection

Kernighan: while n is nonzero, n &= n - 1 drops the lowest set bit and the counter goes up by one.

Reflection

  • n &= n - 1 clears the lowest set bit. The number of loops is the number of 1 bits.
  • A Python negative never runs out of bits. This value is an unsigned 32-bit word.
  • 0 answers 0. The single bit at 2**31, read as unsigned, counts as 1.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Hamming weight of 11. Binary 1011 has three 1-bits.

1
0
0
1
1
2
1
3

n = 11 · c = 0

Key:Active rangeMatchSettledEliminated