Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

Sum of Two Integers in Rust: 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

    RUST · BIT MANIPULATION

    Sum Of Two Integers in Rust, explained

    Problem overview

    The function get_sum receives two i32 values, a and b, and returns a + b without using the + or - operators. Only bitwise operations are allowed.

    For a = 1 and b = 2 the answer is 3. For a = 2 and b = 3 it is 5. For a = -5 and b = 3 it is -2, so negative numbers must work too.

    Approach: add the way you do on paper

    Adding in binary column by column has two parts. In each column, 0 + 0 = 0, 0 + 1 = 1 and 1 + 1 = 10: a digit of 0 stays in the column and a 1 is carried to the next column on the left. The digit left in a column is the XOR of the two bits. A carry appears only where both bits are 1, which is the AND.

    So a ^ b is the sum with all carries left out, and (a & b) << 1 is the carries, already moved one column left. Together they still add up to a + b. The sum has been split into two numbers, and the second one holds the work that remains. Repeat with the pair (sum without carries, carries) until the carries are 0. Then the first number is the complete sum.

    For a = 2, b = 3 (010 and 011), the first pass gives a = 1, b = 4, and the second gives a = 5, b = 0. The answer is 5.

    Step by step

    1. Loop while b != 0. Here a is the sum so far and b the carries still to add. When no carries are left, the sum is complete.
    2. Compute the carries. a & b keeps the columns where both numbers have a 1, and << 1 moves each carry into the column it belongs to. This goes into a new variable, carry, before a changes.
    3. Replace a with a ^ b, the sum without the carries.
    4. Replace b with carry, so the next pass adds the carries to the new a.
    5. Return a as the last expression, without a semicolon.

    The solution in Rust

    impl Solution {
        fn get_sum(mut a: i32, mut b: i32) -> i32 {
            while b != 0 {
                let carry = (a & b) << 1;
                a = a ^ b;
                b = carry;
            }
            a
        }
    }
    

    Rust details worth knowing:

    • mut in the signature. The parameters are declared mut a: i32, mut b: i32, so the function can reassign them. Without mut, the assignments a = a ^ b and b = carry would not compile.
    • Negative numbers need no special case. An i32 is stored in two's complement, and the bit-by-bit addition above is the same one the processor performs. The call get_sum(-5, 3) returns -2.
    • A left shift doesn't overflow-panic. x << 1 simply drops the top bit. Rust panics for a shift amount of 32 or more, but not for bits that are shifted out. That is what makes the loop end: carries move left each pass and eventually fall off the end.
    • The standard way. Normal Rust code would write a + b, which panics on overflow in a debug build and wraps in an optimized build. The explicit method a.wrapping_add(b) says that wrapping is intended. This lesson's loop gives the wrapped result for any pair of i32 values.

    Complexity

    Time: O(1). Each pass moves the lowest carry at least one column to the left. An i32 has 32 columns, so after at most 32 passes the carries have fallen off the left end and b is 0. The count doesn't grow with the size of the values.

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

    Edge cases and common mistakes

    • Adding zero. With b = 0 the loop doesn't run and a comes back.
    • Opposite numbers. get_sum(-1, 1) returns 0. All 32 bits of -1 are 1, so the carry travels through every column before it falls off.
    • Mixed signs and two negatives. get_sum(-5, 3) returns -2, and get_sum(-7, -8) returns -15.
    • Forgetting the shift. Using a & b as the carry, without << 1, puts every carry in the column where it was produced instead of the next one, so the result is wrong.
    • Overwriting a too early. If a becomes a ^ b before the carry is computed, a & b is computed from the wrong a. That is why carry comes first.

    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 = -7, b = -8 gives -15.
    • a = 1000, b = -1000 gives 0.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free