SDE & MLE Prep

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)