Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

Sum of Two Integers in C++: Add with XOR and Carry Shifts

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

    C++ · BIT MANIPULATION

    Sum Of Two Integers in C++, explained

    Problem overview

    The method getSum takes two int values a and b and returns a + b without using the operators + and -. The statement's values stay between -1000 and 1000, and negative numbers must work too.

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

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

    Approach: add column by column

    Think of adding on paper in binary. In each column, 0 + 0 = 0, 0 + 1 = 1, and 1 + 1 = 10: a 0 stays in the column and a 1 is carried into the next one. So the digit left in each column is the XOR of the two bits, and a carry appears exactly where both bits are 1, which is AND, one column to the left.

    That gives two numbers: a ^ b, the sum without carries, and (a & b) << 1, the carries. Their sum is still a + b. So repeat with them as the new a and b: XOR them, compute their carries, and stop when no carry is left. Then the whole sum is in a.

    Each round moves the lowest carry at least one place left, and an int has 32 bits, so after at most 32 rounds it falls off the left end and b becomes 0.

    For a = 2 and b = 3 the lesson's loop goes through these states:

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

    The same loop on a = -5 and b = 3:

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

    Negative numbers need no special case: they are stored in two's complement, and this column-by-column addition is the one a processor does.

    Step by step

    1. Loop while b != 0. a holds the sum so far and b the carries still to add.
    2. Compute the carries into an int named carry: the bits set in both numbers, a & b, shifted left by one. The lesson converts a & b to unsigned int before shifting.
    3. Set a to a ^ b, the sum with the carries left out.
    4. Set b to carry, so the next round adds the carries to a.
    5. Return a.

    The solution in C++

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

    C++ details worth knowing:

    • Why the unsigned int cast. In C++17, shifting a negative int to the left is not allowed (the behaviour is undefined). When a and b are both negative, a & b is negative. Converting it to unsigned int first makes the shift well defined: bits that fall off the left end are dropped.
    • Storing back in an int. The shifted value is converted to int, which keeps the same 32 bits, so a carry into the top bit becomes the sign bit, as two's complement requires.
    • Precedence of the cast. A cast binds tighter than <<, so the cast applies to (a & b) and the shift happens on the unsigned value.
    • Parameters are copies. a and b are passed by value, so the loop can change them without touching the caller's variables.

    Complexity

    Time: O(1). The loop runs at most once per bit of the int, 32 times, whatever the input.

    Space: O(1). Only carry and the two parameters are used.

    Edge cases and common mistakes

    • Adding zero. With b = 0 the loop doesn't run and a is returned as it is. getSum(0, 0) returns 0.
    • Opposite numbers. getSum(-1, 1) and getSum(1000, -1000) both return 0. The carries run through the whole number before they fall off.
    • Two negatives. getSum(-7, -8) returns -15. This is the case where a & b is negative and the cast matters.
    • Forgetting the shift. A carry belongs to the next column. Adding a & b without shifting gives wrong sums.
    • Looping on a. The loop ends when the carries are gone, b == 0, not when a reaches some value.

    Testing

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