Sum of Two Integers

Add two numbers with bit operations alone, by splitting each addition into the bits it leaves and the carries it makes.

Given two integers a and b, return their sum without using the + or - operators. Either number may be negative.

Example 1
Input: a = 1, b = 2
Output: 3
Example 2
Input: a = 2, b = 3
Output: 5
Example 3
Input: a = -7, b = 4
Output: -3
Solution

The Idea

When you add 58 and 67 on paper, you go one column at a time. The ones column gives 8 + 7 = 15, so you write 5 and carry 1 into the tens column. Each column does two jobs: it leaves a digit behind, and it may push a carry one place to the left.

Computers add the same way, only in binary, where every column holds a single 0 or 1, called a bit. In Example 2, 2 is written 010 and 3 is written 011. Number these bit positions from the right, starting at 0. Then 2 has a 1 at position 1, and 3 has 1s at positions 1 and 0.

In binary, 1 + 1 makes 2, which is 10: the column keeps 0 and carries 1. But the problem takes away +, so how can we get the two jobs of every column done with bit operations alone?

Look at the column jobs one by one. The bit a column keeps, if we ignore carries, is 1 when exactly one of the two bits is 1. Java's ^ operator, called XOR (exclusive or), gives exactly that bit in every position at once, so 2 ^ 3 is 001.

A carry, on the other hand, starts only where both bits are 1. Java's & operator, called AND, marks those positions: 2 & 3 is 010. Shifting that one place left with << 1 moves each carry into the column it belongs to, giving 100.

Adding 2 and 3 in binary. Round 1: 010 and 011 give the sum without carries 001 and the carries, one place left, 100. Round 2: 001 and 100 give 101, which is 5, and no carries, so the answer is 5.

The picture shows these numbers for Example 2. In Round 1, a = 2 and b = 3 both have a 1 at position 1, marked in orange. The row "sum without carries (a ^ b)" keeps only the 1 at position 0, worth 1. The row "carries, one place left" holds the carry at position 2, also in orange, worth 4.

The answer is now 1 + 4, the sum without carries plus the carries, and that is another addition. So Round 2 treats them the same way, with a = 1 and b = 4. They have no 1s in the same position, so the sum without carries is 101, which is 5, and the carries row is all 0. With nothing left to carry, 5 is the answer.

So one addition turns into a few rounds of XOR and AND. Each round passes its carries on to the next, and the rounds stop when one of them makes no carries.

Solution Approach

Three things decide the code: what one round computes, why the rounds always stop, and what happens with negative numbers and with sums too big for an int.

One round with XOR and AND

Why does a round keep the total the same? A position where only one number has a 1 keeps that 1 in a ^ b. A position where both have a 1 holds two 1s, worth twice that position's value. XOR drops both, and the carry puts back a single 1 one place to the left, which is worth exactly twice as much. So a + b always equals (a ^ b) + ((a & b) << 1).

So each round may replace a by the sum without carries and b by the carries, and the answer does not change. Both new values come from the old a and b, so the carries are worked out first and kept in a variable named carry before a is overwritten.

When the rounds stop

How many rounds can it take? The carries are made from positions where b has a 1, then moved one place left. So the lowest 1 in b moves up at least one position every round. A Java int has 32 bits, positions 0 to 31, and a carry shifted out past position 31 is dropped, so after at most 32 rounds b is 0.

Example 2 needs two rounds, as the picture shows. The slowest case is a carry that has to travel through every position. Adding -1 and 1 is such a case, and a run that counts rounds shows it takes all 32.

Negative numbers and overflow

How does a Java int hold a negative number? It uses a form called two's complement. In it, -1 is 32 ones, which is why adding 1 to it sends a carry through every position. And -7 is the 32 bits 11111111111111111111111111111001. Add 7, which is 111, and a carry runs up through all 32 positions and falls off the top, leaving 0. That is why this pattern stands for -7.

Because negative numbers are stored so that ordinary column addition works on them, the loop needs no special case. In Example 3, -7 ends in ...11001 and 4 is 00100. They share no 1 bits, so a single round gives ...11101, which is -3, and makes no carries.

What if the true sum does not fit in an int? Integer.MAX_VALUE, 2,147,483,647, is a 0 at position 31 followed by 31 ones. Adding 1 carries all the way into position 31, which in two's complement marks a negative number, so the result is Integer.MIN_VALUE, -2,147,483,648. Java's own + gives that same value, so the method does not try to prevent the wrap; it matches + bit for bit.

Java Solution

The method getSum works in these steps:

  1. Loop while b is not 0. At the start b is the second number; after each round it holds the carries still to be added.
  2. Inside the loop, first work out the carries from the current values, carry = (a & b) << 1.
  3. Then set a to a ^ b, the sum without carries.
  4. Then set b to carry, so the next round adds those carries.
  5. Once b is 0, nothing is left to carry, and a holds the sum, so the method returns a.

A small helper, show, prints one addition with its result. The main method uses it for the three examples, for -1 + 1 and 0 + 0, and for two sums that go past the ends of the int range.

Java
public class SumOfTwoIntegers {

    public static int getSum(int a, int b) {
        while (b != 0) {
            int carry = (a & b) << 1;   // where both bits are 1, a carry goes one place left
            a = a ^ b;                  // the bits added with no carries
            b = carry;                  // the carries still to be added
        }
        return a;
    }

    static void show(int a, int b) {
        System.out.println(a + " + " + b + " = " + getSum(a, b));
    }

    public static void main(String[] args) {
        show(1, 2);
        show(2, 3);
        show(-7, 4);
        show(-1, 1);
        show(0, 0);
        show(Integer.MAX_VALUE, 1);
        show(Integer.MIN_VALUE, -1);
    }
}

Running it prints:

Output
1 + 2 = 3
2 + 3 = 5
-7 + 4 = -3
-1 + 1 = 0
0 + 0 = 0
2147483647 + 1 = -2147483648
-2147483648 + -1 = 2147483647

Look at -7 + 4 = -3: the negative number needs no extra code, just as the bits of Example 3 showed. The line -1 + 1 = 0 is the 32-round case, where the carry climbs through every position and drops off the top. For 0 + 0, b is 0 from the start, so the loop never runs and 0 comes straight back.

The last two lines wrap around. 2147483647 + 1 gives -2147483648, and -2147483648 + -1 gives 2147483647. A separate run of Java's own + on the same two pairs prints the same two values.

The shift in (a & b) << 1 is easy to leave out, and then the method quietly returns wrong sums. With carry = a & b, the carry from position 1 in Example 2 is added back at position 1, where it is worth 2 instead of 4. A test run of that version returns 3 for getSum(2, 3), not 5.

Complexity

Each round does three bit operations, and the 32 bits of an int cap the number of rounds.

  • Time: O(1), because the lowest 1 in b climbs at least one position per round, so no input needs more than 32 rounds, and -1 + 1 needs exactly 32.
  • Space: O(1), because the loop only rewrites a and b and keeps one extra int, carry.