Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

Sum of Two Integers in C#: Adding with XOR and AND

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 receives two int values, a and b, and returns a + b without using the + or - operators. Only bitwise operators are allowed. Both numbers can be negative: the inputs run from -1000 to 1000.

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

    Approach: add column by column, as on paper

    Adding in binary works like adding in decimal. In one 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 column on the left.

    Two bitwise operations capture both parts at once:

    • a ^ b (XOR) is the digit left in each column: 0 for 0+0 and 1+1, and 1 for 0+1. It is the sum with the carries left out.
    • (a & b) << 1 is the carries. AND keeps a bit only where both numbers have a 1, which is exactly where a carry is produced, and shifting left by one moves each carry to the column it goes into.

    The two results still add up to a + b. So repeat the same step on them: XOR gives a new partial sum, AND-and-shift gives new carries. A carry can itself cause another carry, but each round moves the lowest remaining carry at least one column to the left. When no carries are left, the partial sum is the answer.

    Step by step

    1. Loop while b != 0. Here a holds the sum so far and b holds the carries still to be added. When b is 0, everything is in a.
    2. Compute the carries: int carry = (a & b) << 1;. This must happen before a changes, because it needs the old values of both numbers.
    3. Update the sum without carries: a = a ^ b;.
    4. Hand the carries to the next round: b = carry;.
    5. Return a.

    Here are the values of a and b at the end of each round for 2 + 3:

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

    In round one, the middle column has a 1 in both numbers: 2 & 3 is 010, so the carry is 100, which is 4, and 2 ^ 3 is 1. In round two there is no overlap between 1 and 4, so no carries remain and the sum is 5.

    The solution in C#

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

    The C# details worth knowing:

    • Negative numbers need no special case. An int is stored in two's complement, and this column-by-column addition is the same one the processor performs. For -5 + 3 the rounds end at a=-8 b=6 and then a=-2 b=0.
    • Parameters are copies. The loop changes a and b, but the caller's variables stay as they were.
    • Left shift discards the top bit. << on an int never throws: a carry that leaves the 32 bits simply disappears. That is why the loop always ends, and why a sum that doesn't fit in 32 bits wraps.
    • Overflow wraps. GetSum(int.MaxValue, 1) returns -2147483648, the same value that ordinary int addition produces without a checked context. The lesson's inputs are small, so it doesn't come up there.

    Complexity

    Time: O(1). Each round moves the carries at least one column to the left, and an int has 32 columns, so the loop runs at most 32 times however large the values are. Space: O(1). Three int variables.

    Edge cases and common mistakes

    • Zero. GetSum(0, 0) returns 0, and the loop never starts.
    • Opposite numbers. GetSum(-1, 1) and GetSum(1000, -1000) both return 0.
    • Two negatives. GetSum(-7, -8) returns -15.
    • Changing a before computing the carry. a ^ b destroys the information about where both had a 1, so the carries come out wrong.
    • Forgetting the shift. a & b marks the columns that produce a carry, but the carry belongs one column to the left.
    • Using + or - anyway. The exercise's point is the bitwise form: the loop above uses only &, ^, << and comparison.

    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 = -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