Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

Sum of Two Integers in Swift: Bitwise Addition in O(1) Time

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

    SWIFT · BIT MANIPULATION

    Sum Of Two Integers in Swift, explained

    Problem overview

    The method getSum(_ a: Int, _ b: Int) -> Int receives two integers between -1000 and 1000 and returns their sum without using the operators + and -. The tools are the bitwise operators.

    getSum(1, 2) returns 3. getSum(2, 3) returns 5. getSum(-5, 3) returns -2: negative numbers are stored in two's complement, and the same column-by-column addition works for them.

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

    Approach: add the columns, then add the carries

    Think of adding two binary numbers on paper, one column at a time. In one column, 0 + 0 is 0, 0 + 1 is 1, and 1 + 1 is 10: a 0 stays in that column and a 1 is carried into the next one on the left.

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

    The two numbers, x ^ y and the shifted carries, still add up to x + y. So repeat the same step with them: XOR them, compute the new carries, and continue until no carry is left. Then the whole sum is in the XOR part.

    Each round moves the lowest carry at least one place to the left. A Swift Int has 64 bits, so after at most 64 rounds the carries fall off the left end and become 0. The number of rounds doesn't grow with the size of the input.

    Step by step

    1. Copy the parameters into var x = a and var y = b, since Swift parameters are constants. x holds the sum so far and y the carries still to add.
    2. Loop while y != 0. With no carries left, nothing more needs adding.
    3. Compute the carries into let carry = (x & y) << 1. This has to happen before x changes.
    4. Add without carrying: x = x ^ y.
    5. Make the carries the next number to add: y = carry.
    6. Return x.

    The solution in Swift

    class Solution {
        func getSum(_ a: Int, _ b: Int) -> Int {
            var x = a
            var y = b
            while y != 0 {
                let carry = (x & y) << 1
                x = x ^ y
                y = carry
            }
            return x
        }
    }
    

    The Swift details worth a closer look:

    • Constant parameters. The loop changes both numbers, so they are copied into vars first.
    • Shifts don't trap. Ordinary arithmetic on Int that overflows crashes the program in Swift, but << simply discards the bits that move past the left end: Int.max << 1 is -2. That is why the carry can fall off the end and become 0 instead of crashing.
    • Two's complement. A negative Int has its upper bits set, and nothing in the loop treats the sign specially.
    • let carry. The carry is computed once per round and never changes, so let fits.

    Tracing two additions

    For getSum(2, 3), the state of x and y after each turn of the loop:

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

    In binary, 010 + 011 first gives 001 with a carry of 100, and adding those leaves no further carry. The result is 5.

    For getSum(-5, 3):

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

    The result is -2, the right answer, with no special handling of the sign.

    Complexity

    Time: O(1). Each round pushes the carries at least one place left, and an Int has 64 bits, so the loop runs at most 64 times whatever the values are.

    Space: O(1). Only x, y and carry are stored.

    Edge cases and common mistakes

    • One number is 0. getSum(5, 0) returns 5 at once, because y is already 0.
    • Opposite numbers. getSum(7, -7) returns 0. getSum(-1, 1) also returns 0, and it is the slow case: the carry travels through all 64 columns, so the loop runs 64 times.
    • Two negatives. getSum(-1000, -1000) returns -2000.
    • Forgetting the shift. A carry belongs in the next column to the left. Using x & y without << 1 adds it in the wrong place.
    • Updating x before computing the carry. After x = x ^ y, the value x & y is different. Compute carry first.
    • Using + or - anywhere. The task forbids them, including x - 1 or y += carry.

    Testing

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