0:00 / 0:00

Add two numbers without plus or minus. XOR adds each column, AND shifted left is the carry, and you repeat until the carry is zero.

▼

The problem

LeetCode 371 (Medium). Given two integers a and b, return their sum without using the operators + and -.

Example: a = 2, b = 3 → 5 (the LeetCode example).

TRY IT ON LEETCODE ▶

The solution

def getSum(a, b):
    MASK = 0xFFFFFFFF            # 32 bits
    while b != 0:
        a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
    if a > 0x7FFFFFFF:           # sign bit set
        a = ~(a ^ MASK)          # back to negative
    return a

Transcript

Sum of Two Integers. Given two integers, a and b, return their sum, without using the plus or minus operators. We'll build addition ourselves, out of bits.

Take a equals two and b equals three. The answer is five. Picture each number as a wire, and each one bit as a bird perched on it. Two is one zero: one bird. Three is one one: two birds. Five is one zero one.

The naive way counts up: add one to a, b times. But adding one is still a plus, and it takes b steps, so adding a billion takes a billion.

Instead, add one column at a time, like at school. One bird alone means the sum bit is one. That's XOR. Two birds mean the sum bit is zero, and one bird carries to the next column on the left. That's AND, shifted left by one.

Now the trick. a plus b equals the XOR plus the carry, and that's just another sum. So repeat: a takes the XOR, b takes the carry, until the carry is zero. Two and three give one, carry four. Then five, carry zero. Done.

Now a bigger one: eleven plus seven. Round one: XOR twelve, carry six. Round two: ten, carry eight. Round three: two, carry sixteen. Round four: eighteen, carry zero. The carry rippled left until nothing was left to carry. Eighteen.

In code, loop while b is not zero. Python integers never overflow, so mask both to thirty two bits, and negatives work as two's complement. At the end, if a is past the largest positive int, its sign bit is set, so convert it back.

Each round, the carry's lowest bit moves at least one place left, so there are at most thirty two rounds. Time is order one, and space is order one.

XOR adds, AND carries, shift and repeat. That's Sum of Two Integers.