Sum of Two Integers
Problem
Given two integers a and b, return their sum without using the + or − operators.
Split addition into two halves: a ^ b is the sum if you forget about carries, and (a & b) << 1 is exactly the carries shifted into their correct columns. Repeat until the carry becomes 0.
In languages with fixed-width integers (Java/C++), the loop keeps b as the carry; in Python you mask with 0xFFFFFFFF and reinterpret the result as a 32-bit signed value at the end.
a = 5, b = 712def get_sum(a, b):
mask = 0xFFFFFFFF
while b & mask:
carry = (a & b) << 1
a = (a ^ b) & mask
b = carry & mask
return a if a < 0x80000000 else ~(a ^ mask)
function getSum(a, b) {
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
int getSum(int a, int b) {
while (b != 0) {
unsigned carry = (unsigned)(a & b) << 1;
a = a ^ b;
b = (int)carry;
}
return a;
}
Explanation
We add two numbers without + by rebuilding what an adder circuit does: split each step into a sum without carries and the carries, then repeat until there are no carries left.
The sum-without-carry of a and b is a ^ b — XOR adds each column but throws away any carry. The carries themselves are (a & b) << 1: a carry happens only where both bits are 1, and it belongs in the next column up, hence the left shift.
We loop, setting a = a ^ b and b = carry, until b becomes 0. When there are no more carries to fold in, a holds the final sum.
This Python version uses mask = 0xFFFFFFFF to keep everything within 32 bits, since Python integers are otherwise unbounded. The final line reinterprets the masked result as a 32-bit signed value so negative sums come out correctly.
Example: a = 5 = 101, b = 7 = 111. First a ^ b = 010 and carry = 1010; folding repeats until the carry clears, ending at 12.