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

Bit Manipülasyonu

Rehber 3 / 6 · Yol 3 / 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.

Power of Two

Problem (restated)

Return true if n is a power of two (positive integer with exactly one bit set).

Intuition

Powers of two are 1,2,4,8… Clearing the lowest set bit of such n yields 0: n & (n-1) == 0, and n > 0.

Approaches

n & (n-1) == 0

Tested only
Time O(1)Space O(1)

Idea. Reject non-positive. One-liner bit trick.

Walkthrough. 16 → true; 3 → false; 0 → false.

Trade-offs. Log loop also works; bit check is O(1).

Solution
export function isPowerOfTwo(n: number): boolean {
  return n > 0 && (n & (n - 1)) === 0;
}
export function isPowerOfTwo(n: number): boolean {
  return n > 0 && (n & (n - 1)) === 0;
}

Template connection

Bit tricks: lowest-set-bit clear.

Reflection