Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

Sum of Two Integers in Kotlin: 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 6
    Ctrl + Enter to check

    KOTLIN · BIT MANIPULATION

    Sum Of Two Integers in Kotlin, explained

    Problem overview

    The function getSum receives two Int values, a and b, and returns a + b without using the operators + and -. The lesson uses bitwise operations instead.

    For a = 2 and b = 3 the answer is 5. In binary, 010 + 011: the middle column has a 1 in both numbers, so it leaves a 0 and carries a 1 to the left, and the sum is 101. Negative numbers work too: -5 + 3 is -2.

    Approach: add the columns, then add the carries

    Binary addition on paper handles one column at a time: 0 + 0 = 0, 0 + 1 = 1, and 1 + 1 = 10, which leaves 0 and carries 1 into the next column. Two bitwise operations capture this:

    • x xor y is the digit left in each column, with the carries ignored. It is 1 where exactly one of the bits is 1.
    • (x and y) shl 1 is the carries. A carry appears where both bits are 1, and it belongs one column to the left.

    The sum without carries and the carries still add up to the full sum. So replace the pair (x, y) by (x xor y, carries) and repeat. Each round moves the lowest remaining carry at least one place left. An Int has 32 bits, so after at most 32 rounds the carries fall off the left end, y becomes 0, and everything is in x. The number of rounds doesn't grow with the values: the time is O(1).

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

    Step by step

    1. Copy the parameters into two vars, x set to a and y set to b, because Kotlin parameters are read-only. x holds the sum so far and y the carries still to add.
    2. Loop while y != 0. When no carries are left, there is nothing more to add.
    3. Compute the carries in a val named carry: (x and y) shl 1. It must be computed first, because the next line changes x.
    4. Add without carries: x = x xor y.
    5. Move the carries to y: y = carry, so the next round adds them.
    6. Return x.

    The solution in Kotlin

    class Solution {
        fun getSum(a: Int, b: Int): Int {
            var x = a
            var y = b
            while (y != 0) {
                val carry = (x and y) shl 1
                x = x xor y
                y = carry
            }
            return x
        }
    }
    

    For a = 2 and b = 3 the loop takes two rounds:

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

    For a = -5 and b = 3 it also takes two:

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

    The Kotlin details worth knowing:

    • Bitwise operators are words. Kotlin writes and, xor and shl as infix functions instead of &, ^ and <<.
    • Parentheses. In (x and y) shl 1 they make the order explicit. Both and and shl are named infix functions with the same precedence, so Kotlin evaluates a chain of them left to right.
    • Two's complement. -5 is stored as 11111111111111111111111111111011. The loop treats it like any other 32 bits.
    • Int wraps silently. getSum(Int.MAX_VALUE, 1) returns -2147483648, the same as Int.MAX_VALUE + 1 does. The lesson's inputs stay between -1000 and 1000, so this never happens in its tests.

    Complexity

    Time: O(1). The loop runs at most 32 times, once per bit of an Int, whatever the inputs are.

    Space: O(1). The function keeps three integers.

    Edge cases and common mistakes

    • Zero as an input. If b is 0, the loop doesn't run, and a is returned.
    • Opposite numbers. getSum(7, -7) and getSum(-1, 1) both return 0.
    • Computing carry after changing x. Once x has been replaced by x xor y, the AND no longer describes the columns where both bits were 1.
    • Forgetting the shift. x and y marks the columns that carry, but the carry goes into the next column to the left. Without shl 1 the result is wrong.
    • Special-casing negatives. It isn't needed. getSum(-1000, -1000) returns -2000 with the same code.

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