Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

Sum of Two Integers in Scala: Bitwise Addition with XOR and Carry

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 6
    Ctrl + Enter to check

    SCALA · BIT MANIPULATION

    Sum Of Two Integers in Scala, explained

    Problem overview

    The method getSum(a: Int, b: Int): Int returns a + b without using the operators + or -. Only bitwise operations are allowed, and the values lie between -1000 and 1000.

    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.

    Approach: add column by column

    Add two binary numbers as you would on paper. In one column, 0 + 0 = 0, 0 + 1 = 1 and 1 + 1 = 10: a 0 stays in the column and a 1 is carried to the next column on the left. Two bit operations capture this:

    • The digit left in each column is the XOR of the two bits: x ^ y is the sum with the carries left out.
    • A carry appears only where both bits are 1, which is x & y, and it belongs one column to the left, so the carries are (x & y) << 1.

    The two results still add up to the original sum: x + y equals (x ^ y) + ((x & y) << 1). That is an addition again, but with carries that sit further left. Repeat the same step on the new pair. Each round pushes the lowest carry at least one place to the left, and after at most 32 rounds it falls off the end of an Int, so the carries become 0 and the sum is in x.

    Step by step

    1. Copy a and b into var x and var y, since Scala parameters can't be reassigned. x holds the sum so far and y the carries still to add.
    2. Loop while (y != 0): while a carry exists, there is something left to add.
    3. Compute val carry = (x & y) << 1 first, before x changes.
    4. Set x = x ^ y.
    5. Set y = carry.
    6. End the method with x, the last expression.

    The solution in Scala

    class Solution {
        def getSum(a: Int, b: Int): Int = {
            var x = a
            var y = b
            while (y != 0) {
                val carry = (x & y) << 1
                x = x ^ y
                y = carry
            }
            x
        }
    }

    Scala details

    • The order of the loop body matters: carry must be computed from the old x and y, so it comes before x is overwritten.
    • carry is a val, because it is set once per round. x and y are vars.
    • << shifts left on Int and bits that go past position 31 are discarded, with no error. That is why the carries eventually vanish.
    • Negative numbers need no special handling. An Int stores them in two's complement, and the bit-by-bit addition above is what the processor does itself. In two's complement, -5 is 11111111111111111111111111111011.

    Tracing two examples

    For a = 2 and b = 3, the values after each round are:

    round 1: x=1 y=4
    round 2: x=5 y=0

    In round 1, 2 ^ 3 is 1 (binary 01) and the carry is (2 & 3) << 1, which is 4. Round 2 adds 1 and 4 with no overlap, so x becomes 5 and the carry is 0.

    For a = -5 and b = 3:

    round 1: x=-8 y=6
    round 2: x=-2 y=0

    The loop ends with -2, the right answer for a negative operand.

    Complexity

    Time is O(1): the loop runs at most once per bit of an Int, 32 rounds, whatever the values are. Space is O(1): three integers.

    Edge cases and common mistakes

    • Zeros: getSum(0, 0) never enters the loop and returns 0. If only b is 0 the loop is skipped and a comes back.
    • Opposites: getSum(-1, 1) and getSum(1000, -1000) both return 0. The carry travels all the way to the left end and drops off.
    • Both negative: getSum(-7, -9) returns -16.
    • Overflow: outside the lesson's range, results wrap like ordinary Int addition. getSum(Int.MaxValue, 1) returns -2147483648, the same as Int.MaxValue + 1.
    • Shifting the wrong value: shift the AND, not the XOR: (x & y) << 1. Shifting x ^ y gives a different number entirely.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free