Algo-Sim › Matrix & Bit Manipulation

Sum of Two Integers

Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Add two integers without + or −: XOR adds without carries, AND shifted left gives the carries; repeat until no carry is left.

Problem

Given two integers a and b, return their sum without using the + or - operators.

Constraints

Edge cases to test

Follow-up questions

Why does it loop forever in Python?
Python ints are unbounded, so a negative carry never shifts out. Mask with 0xFFFFFFFF each round and convert back to signed at the end.
How many iterations can it take?
At most 32: each round moves the carry at least one bit left.

Solution

Java

public int getSum(int a, int b) {
    while (b != 0) {
        int carry = (a & b) << 1;
        a ^= b;
        b = carry;
    }
    return a;
}

Python

def get_sum(a, b):
    mask = 0xFFFFFFFF
    a, b = a & mask, b & mask
    while b != 0:
        carry = ((a & b) << 1) & mask
        a, b = a ^ b, carry
    return a if a <= 0x7FFFFFFF else ~(a ^ mask)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int getSum(int a, int b) {
        uint32_t x = uint32_t(a), y = uint32_t(b);
        while (y != 0) {
            uint32_t carry = (x & y) << 1;
            x ^= y;
            y = carry;
        }
        return int32_t(x);
    }
};

More Matrix & Bit Manipulation problems