medium

Sum of Two Integers

Add two integers together without using the + or - operators.

1. Define the problem

Sum of Two Integers

Given two integers a and b, return their sum without using the operators + or -. XOR gives the sum ignoring carries , and AND-then-shift-left gives just the carries . Keep adding those two pieces together — a ^ b, and (a & b) << 1 as the new b — until there is no carry left.

Constraints

  • -1000 ≤ a, b ≤ 1000

Example

Inputa = 1, b = 2
Output3

Explanation 1 (01) and 2 (10) share no bit positions, so a ^ b already equals 3 with no carry.

2. Know the words first

In plain terms

Carry
The 1 that spills into the next bit position when two 1 bits are added together — the same carry you'd write above the next column doing addition by hand, but here it becomes (a & b) shifted one place left.
3. Visualize the solution

Loop XOR (sum) and AND-shift (carry) until no carry remains

Loop XOR (sum) and AND-shift (carry) until no carry remains
Statusinit

a=2 (010), b=3 (011). a & b = 010, so carry = 010 << 1 = 100.

What happens in this step

2 & 3
  2 = 00000010
  3 = 00000011
      --------
      00000010  =  2

carry = 2 << 1
  2 shifted left 1 → 00000100  =  4

The overlapping bit (bit 1, value 2) is where both a and b already have a 1 — that column will carry. Shifting it left one place lines it up for the next column: carry = 4.
Step 1 of 4

Steps to visualize

  1. While b is not 0, compute carry = (a & b) << 1 — the bits that would carry over.
  2. Set a = a ^ b — the sum of a and b ignoring any carry.
  3. Set b = carry, and repeat with the new a and b.
  4. Once b reaches 0, a holds the final sum.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Loop XOR (sum) and AND-shift (carry) until no carry remains
Statusinit

a=2 (010), b=3 (011). a & b = 010, so carry = 010 << 1 = 100.

What happens in this step

2 & 3
  2 = 00000010
  3 = 00000011
      --------
      00000010  =  2

carry = 2 << 1
  2 shifted left 1 → 00000100  =  4

The overlapping bit (bit 1, value 2) is where both a and b already have a 1 — that column will carry. Shifting it left one place lines it up for the next column: carry = 4.
Step 1 of 4
5. Solution

Solution

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

  return a;
}
Time
O(1), bounded by 32-bit width
Space
O(1)
6. Test cases

Test cases

InputExpectedCovers
a = 1, b = 23example from the docstring
a = 2, b = 35addition that produces an intermediate carry
a = -2, b = 31a negative and a positive operand
a = 0, b = 00smallest valid input, both operands zero
a = -5, b = -3-8two negative operands
a = 100, b = 200300larger positive operands with multiple carry rounds