Back to solutions
Sum of Two Integers
MediumBit ManipulationCompute the sum of two integers without using the + or - operators.
Constraints
- -1000 <= a, b <= 1000
Bitwise add with carry
Time O(1) (fixed 32 bits)Space O(1)
The XOR of two numbers is the sum without carries; the AND shifted left is the carry. Repeat until there is no carry left.
int getSum(int a, int b) {
while (b != 0) {
unsigned carry = (unsigned)(a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}