Sum of Two Integers

Difficulty: Medium

Add two integers together (either one may be negative) - without using the + or - operators anywhere in your solution.

Examples

Input: a = 1, b = 2
Output: 3

Input: a = 2, b = 3
Output: 5

Input: a = -2, b = 3
Output: 1

Constraints

  • -1000 <= a, b <= 1000

Approach

Binary addition works like decimal addition: adding two bits gives a digit and sometimes a carry into the next position.

  • XOR gives the digit without the carry: 1+0 and 0+1 give 1; 0+0 and 1+1 give 0.
  • AND is 1 only when both bits are 1, which is exactly when a carry happens.

So XOR a and b to get the sum ignoring carries. Compute the carries with AND, shifted left one position, since a carry lands one bit higher. Then add the carry back with the same XOR/AND steps, and repeat until there's no carry left.

With at most 32 bits to carry through, this finishes quickly.

Solutions

Brute Force - Step One Unit at a Time

Increment a b times (or decrement it if b is negative). This avoids + and -, but the work grows with the size of b and misses the point of the problem.

function getSum(a, b) {
  if (b >= 0) {
    for (let i = 0; i < b; i++) a++;
  } else {
    for (let i = 0; i < -b; i++) a--;
  }
  return a;
}

Time: O(|b|) · Space: O(1)

Optimal - Bitwise XOR for Sum, AND for Carry

Compute a 'carry-free sum' with XOR and the carry with AND shifted left by one. Feed the carry back in until it's 0. The running value is then the true sum.

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

Time: O(1) - bounded by the fixed 32-bit width of the numbers · Space: O(1)