İçeriğe atla
ΣDSA Patterns
Menü
Dil

Bit Manipülasyonu

Rehber 2 / 6 · Yol 2 / 6

Bu yazı henüz İngilizce. Arayüz Türkçe; içerik çevirisi sürüyor.

Demo önizleme: Bu çözümler otomatik test paketini geçiyor ama insan tarafından incelenmedi. Trade-off ve yazıları taslak olarak değerlendirin.

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