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

Bit Manipülasyonu

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

Sum of Two Integers

Problem (restated)

Return a+b without using + or, operators.

Intuition

a^b is sum without carry; (a&b)<<1 is carry. Iterate until carry is 0.

Approaches

XOR + carry loop

Tested only
Time O(1) 32-bitSpace O(1)

Idea. Full-adder simulation over bits. Python needs 32-bit mask for negatives.

Walkthrough. 1+2 → 3; -1+1 → 0.

Trade-offs. Built-in + is fine in production; problem is a bit-op exercise.

Solution
export function getSum(a: number, b: number): number {
  while (b !== 0) {
    const carry = (a & b) << 1;
    a = a ^ b;
    b = carry;
  }
  // JS bitwise is 32-bit signed already for |0
  return a | 0;
}
export function getSum(a: number, b: number): number {
  while (b !== 0) {
    const carry = (a & b) << 1;
    a = a ^ b;
    b = carry;
  }
  // JS bitwise is 32-bit signed already for |0
  return a | 0;
}

Template connection

Bitwise arithmetic simulation.

Reflection