Sum of Two Integers

medium bit manipulation math

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.

Inputa = 5, b = 7
Output12

def 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;
}
Time: O(1) (≤ 32 iterations) Space: O(1)