Sum of two integers

Add two integers without + or -. XOR adds each column and ignores carries; AND then shift left finds the carries. Repeat until no carry is left.

Time O(1) (at most 32 rounds)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

In one binary column, 0 + 0 = 0, 0 + 1 = 1 and 1 + 1 = 0 carry 1. The no-carry part is exactly XOR. A carry appears only where both bits are 1, which is AND, and it belongs one column to the left, so shift it left by one. Now a + b = (a ^ b) + ((a & b) << 1): the same problem with a new pair. Repeat until the carry is 0; each round the carries move left, so it always ends.

Code

public int GetSum(int a, int b) {
    while (b != 0) { // b holds the carries still to be added
        int sum = a ^ b; // add every column, ignoring carries
        int carry = (a & b) << 1; // a column with two 1s carries into the next column
        a = sum;
        b = carry;
    }
    return a;
}

Tips

In the .NET library

C# shifts and bitwise operators never throw on overflow, even in a checked context, so (a & b) << 1 quietly drops a carry out of bit 31. Python ints never overflow, so the same loop needs a 0xFFFFFFFF mask there.