371. Sum of Two Integers
Problem
Return the sum of integers a and b without using the + or - operators.
Example: a = 2, b = 3 → 5
Constraints: −1000 ≤ a, b ≤ 1000.
Without +: a ^ b is the sum without carries, (a & b) << 1 the carries. Repeat until no carry. Python needs a 32-bit mask.
a = 0101 (5), b = 0011 (3)
xor 0110 carry 0010 -> a=0110 b=0010
xor 0100 carry 0100 -> a=0100 b=0100
xor 0000 carry 1000 -> a=0000 b=1000
xor 1000 carry 0000 -> 8
Complexity: O(32).
class Solution:
def getSum(self, a: int, b: int) -> int:
mask = 0xFFFFFFFF
while b & mask:
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
a &= mask
return a if a < 1 << 31 else a - (1 << 32)
assert Solution().getSum(1, 2) == 3
assert Solution().getSum(2, 3) == 5
assert Solution().getSum(-1, 1) == 0
assert Solution().getSum(-12, -8) == -20
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a ^= b;
b = carry;
}
return a;
}
}
func getSum(a int, b int) int {
for b != 0 { // sum without carry, then the carry shifted left; ints wrap, so negatives work
a, b = a^b, (a&b)<<1
}
return a
}