Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

Sum of Two Integers in Go: Adding with XOR and Carries

Practice O(1) Read the full explanation

You get two integers, a and b.

Return a + b. Your code may not use + or -.

 

Example 1:

Input: a = 4, b = 9
Output: 13
Explanation: In binary, this is 0100 + 1001.
No column has two 1s, so nothing carries.
The sum is 1101, which is 13.

Example 2:

Input: a = 7, b = 1
Output: 8
Explanation: In binary, this is 111 + 001.
The last column has two 1s.
It writes 0 and carries 1.
In each of the next two columns, the carry meets a 1.
Each time, it writes 0 and carries 1 again.
The sum is 1000, which is 8.

Example 3:

Input: a = -9, b = 4
Output: -5
Explanation: The computer stores negative numbers in two's complement.
Adding column by column works for them too.

 

Constraints:

  • a and b are each from -1,000 to 1,000.
Note:

Use bitwise operations instead of + and -. Your algorithm should run in O(1) time and use O(1) extra space: it may loop once for each bit of the integer type, but no more.



Add the two numbers in binary, one column at a time, as you would on paper. In a column, 0 + 0 = 0, 0 + 1 = 1, and 1 + 1 = 10: a 0 in that column and a 1 carried into the next one. The digit left in each column is the XOR of the two bits, and a carry appears only where both bits are 1: the AND of the two bits.

a XOR b is the sum without the carries, and (a AND b) shifted left by one place is the carries. Those two numbers still add up to a + b, so repeat with them: XOR them, compute their carries, and stop when there is no carry left.

Each round moves the carries at least one place to the left, so the loop runs at most once per bit of the integer: 32 times for a 32-bit integer. That doesn't depend on the input: O(1) time.
We keep a few numbers, so the extra space is O(1).
STEP 1 OF 5
    Ctrl + Enter to check

    GO · BIT MANIPULATION

    Sum Of Two Integers in Go, explained

    Problem overview

    The function getSum receives two integers, a and b, and must return a + b without using the operators + and -. The values are between -1000 and 1000, and negative numbers are allowed.

    For a = 1 and b = 2 the answer is 3. For a = 2 and b = 3 it is 5, and for a = -5 and b = 3 it is -2.

    The lesson asks for O(1) time and O(1) extra space: the loop may run once for each bit of the integer type, but no more.

    Approach: add column by column, as on paper

    Adding in binary works like adding in decimal, one column at a time. In a column, 0 + 0 is 0, 0 + 1 is 1, and 1 + 1 is 10: a 0 stays in that column and a 1 is carried to the next one on the left.

    That gives two bitwise pieces:

    • a ^ b (XOR) is the digit left in each column, which is the sum with the carries left out.
    • (a & b) << 1 is the carries: a carry appears only where both numbers have a 1, and it belongs one column to the left.

    The two results still add up to a + b, so the problem has been replaced by a similar one with a smaller carry. Repeat: XOR them, compute their carries, and stop when there are no carries left. Then the whole sum is in the XOR part.

    For a = 2 and b = 3 (binary 010 and 011), the values after each round of the loop are:

    a = 1 b = 4
    a = 5 b = 0
    result 5
    

    In the first round the middle column has two 1s, so it leaves a 0 and carries a 1 to the left. In the second round, 1 and 100 share no column, nothing is carried, and a holds 5.

    Negative numbers need no special case. Go stores them in two's complement, and this column-by-column addition is the one a processor does itself. With a = -5 and b = 3 the loop prints:

    a = -8 b = 6
    a = -2 b = 0
    result -2
    

    Step by step

    1. Start a loop that runs while b != 0. Here a holds the sum so far and b the carries still to add. In Go, a for with only a condition is the while loop.
    2. Compute the carries and store them in carry, declared with :=: (a & b) << 1.
    3. Set a to a ^ b, the sum without the carries.
    4. Set b to carry, so the next round adds those carries to a. The order matters: carry must be computed before a is overwritten, because it needs the old a.
    5. Return a once no carries are left.

    The solution in Go

    func getSum(a int, b int) int {
        for b != 0 {
            carry := (a & b) << 1
            a = a ^ b
            b = carry
        }
        return a
    }
    

    The Go details worth knowing:

    • int is 64 bits. The loop therefore ends within 64 rounds: each round moves the lowest carry at least one place left, and after enough rounds it falls off the left end.
    • Shifts drop bits silently. A carry pushed past the top bit disappears. That is what ends the loop for the hardest case, described below.
    • ^ between two numbers is XOR. The same symbol in front of a single number flips its bits.
    • Parameters are copies. The function changes a and b freely without touching the caller's variables.

    The longest case

    The slowest inputs are a negative number and a positive one of the same size. With a = -1 and b = 1, every round produces a single carry that moves one place left, so the values run through a = -2, b = 2, then a = -4, b = 4, and so on. After 64 rounds the carry has moved off the left end:

    a = -9223372036854775808 b = -9223372036854775808
    a = 0 b = 0
    result 0
    

    That is the last two rounds, and the answer, 0, is right. The loop is still bounded by the width of the type, which is why the algorithm is O(1).

    Complexity

    Time: O(1). The loop runs at most once per bit of an int, 64 times, whatever a and b are. Each round does a constant number of bit operations.

    Space: O(1). The function keeps a, b and carry.

    Edge cases and common mistakes

    • Zero. getSum(0, 0) skips the loop and returns 0. If b is 0 from the start, a is returned as it is.
    • Opposite numbers. getSum(7, -7) and getSum(-1, 1) both return 0.
    • The extremes. getSum(-1000, -1000) returns -2000 and getSum(1000, 1000) returns 2000.
    • Overwriting a too early. If a = a ^ b runs before the carry is computed, the carry is built from the wrong value of a.
    • Forgetting the shift. A carry belongs in the next column. Using a & b without << 1 adds it in the wrong place.
    • Handling negatives separately. Not needed; adding a special case only adds bugs.

    Testing

    • a = 1, b = 2 gives 3.
    • a = 2, b = 3 gives 5.
    • a = -5, b = 3 gives -2.
    • a = 0, b = 0 gives 0.
    • a = -1, b = 1 gives 0.
    • a = -1000, b = -1000 gives -2000.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free