Home
DSA Patterns
Bit Manipulation
Sum of Two Integers
Sum of Two Integers
Add two integers without the + or - operators: XOR adds without carrying, and AND shifted left is the carry.
Problem Understanding
Sum of Two Integers: given two integers a and b, return their sum without using the + or - operators.
Examples: a = 1, b = 2 returns 3; a = 2, b = 3 returns 5.
The Intuition: Split Addition Into Sum and Carry
Binary addition does two things in every column: it writes a digit and it may carry one to the left. Bitwise operators can do each part separately:
a ^ bwrites every column's digit and ignores the carries.a & bmarks the columns that carry (both bits are1), and<< 1moves those carries one column left.
Adding the carry to the carry-less sum is the same problem again, with a new a and b. Each round pushes the carries further left, so they eventually run out, and the loop stops when b, the carry, is 0.
Interactive Walkthrough
Each round shows a, b, their XOR and their carry, bit 0 on the right. Columns where both a and b are 1 are marked: those are the carries, and they reappear one column left in the carry row, which becomes the next round's b.
Dry Run Table
Input: a = 2, b = 3
| Round | a |
b |
a ^ b |
(a & b) << 1 |
|---|---|---|---|---|
| 1 | 010 | 011 | 001 | 100 |
| 2 | 001 | 100 | 101 | 000 |
The carry is 0 after round 2, so the answer is 101 = 5.
The Solution Template
Repeat XOR for the sum and AND-shift for the carry until the carry is zero.
Sum of Two Integers Code
1var getSum = function(a, b) {2 while (b !== 0) {3 const carry = (a & b) << 1;4 a ^= b;5 b = carry;6 }7 return a;8};
Edge Cases & Common Mistakes
- Negative numbers: two's complement makes the same loop correct in fixed-width languages; the carry eventually shifts out of bit 31.
- Python: without the 32-bit mask, a negative carry never shifts out and the loop never ends.
- C and C++: left-shifting a negative signed value is undefined behaviour in older standards, so shift as
unsigned. - Updating
abefore computing the carry: compute(a & b) << 1from the olda, then XOR.
Summary
Addition is a carry-less sum plus a carry. a ^ b is the first, (a & b) << 1 the second; repeat with those two as the new inputs until the carry is 0. At most 32 rounds for 32-bit integers.
More practice: DSA interview questions with answers · patterns cheat sheet
