Skip to content
ΣDSA Patterns
Menu
Language

Bit Manipulation

Guide 2 of 6 · Path 2 of 6

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

Tested only
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

Bit manipulation set-bit checks.

Reflection