Q48: Sum of Two Integers (Bitwise Logic)

Calculate the sum of two integers a and b without using the operators + and -.

Bitwise Addition
function getSum(a, b) {
  while (b !== 0) {
    let carry = (a & b) << 1;
    a = a ^ b;
    b = carry;
  }
  return a;
}

console.log(getSum(5, 7)); // 12
💡 a & b finds matching bit carries, shifted left by 1. a ^ b calculates half-adder sum. Process repeats until carry b becomes 0.
Key Takeaways
  • XOR operator (^) calculates sum without carry.
  • AND operator (&) followed by bitwise left shift (<< 1) calculates carry values.
Knowledge Check

Which bitwise operator computes binary addition without handling carry bits?