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
a = 1, b = 23Explanation 1 (01) and 2 (10) share no bit positions, so a ^ b already equals 3 with no carry.
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.
Loop XOR (sum) and AND-shift (carry) until no carry remains
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.Steps to visualize
- While b is not 0, compute carry = (a & b) << 1 — the bits that would carry over.
- Set a = a ^ b — the sum of a and b ignoring any carry.
- Set b = carry, and repeat with the new a and b.
- Once b reaches 0, a holds the final sum.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
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.Solution
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)
Test cases
| Input | Expected | Covers |
|---|---|---|
a = 1, b = 2 | 3 | example from the docstring |
a = 2, b = 3 | 5 | addition that produces an intermediate carry |
a = -2, b = 3 | 1 | a negative and a positive operand |
a = 0, b = 0 | 0 | smallest valid input, both operands zero |
a = -5, b = -3 | -8 | two negative operands |
a = 100, b = 200 | 300 | larger positive operands with multiple carry rounds |