Start learning free

LESSON 308 OF 314 · BIT MANIPULATION

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

    TYPESCRIPT · BIT MANIPULATION

    Sum Of Two Integers in TypeScript, explained

    Problem overview

    The method getSum receives two integers, a and b, and returns a + b without using the operators + and -. The values are between -1000 and 1000, and the note asks for O(1) time and space, which means it may loop once per bit of the integer type but no more.

    For a = 1 and b = 2 the binary addition is 01 + 10: no column has a 1 in both numbers, nothing is carried, and the sum is 11, which is 3. For a = 2 and b = 3, 010 + 011 has a 1 in both numbers in the middle column, which leaves a 0 and carries a 1 to the left, giving 101, which is 5. Negative numbers work too: -5 + 3 is -2.

    Approach: add column by column, as on paper

    When you add two binary numbers on paper, each column gives a digit and possibly a carry: 0 + 0 = 0, 0 + 1 = 1, and 1 + 1 = 10, a 0 in that column and a 1 carried into the next one on the left.

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

    These two numbers still add up to a + b, so we can repeat the step with them: XOR them, compute their carries, and stop when no carry is left. Each round moves the lowest carry at least one place to the left, and the bitwise operators work on 32-bit integers, so after at most 32 rounds the carries fall off the left end. That number doesn't depend on the input, which is why the time is O(1).

    Here are the rounds for a = 2 and b = 3, showing the values of a and b at the end of each round:

    round  a  b
    1      1  4
    2      5  0
    

    Once b is 0, a holds the sum, 5.

    Step by step

    1. Loop while b !== 0. Here a holds the sum so far and b the carries still to add. When there are none, the sum is all in a.
    2. Compute the carries: (a & b) << 1. The AND keeps a bit only where both numbers have a 1, and the shift moves each one place left.
    3. Add without carries: a = a ^ b. Each column is added on its own, and 1 + 1 gives 0. The carry that column should make was saved in the previous step.
    4. Set b to the carries, so the next round adds them to a. The value a + b stays the same from round to round: part of it just moves from one number to the other.
    5. Return a.

    The solution in TypeScript

    class Solution {
        getSum(a: number, b: number): number {
            while (b !== 0) {
                let carry = (a & b) << 1;
                a = a ^ b;
                b = carry;
            }
            return a;
        }
    }
    

    Some TypeScript details:

    • Negative numbers need nothing special. The bitwise operators convert their operands to signed 32-bit integers in two's complement, which is how processors add. For a = -5 and b = 3 the rounds give a = -8, b = 6 and then a = -2, b = 0, so the result is -2.
    • The carry is computed first. carry must be calculated before a changes, because it needs the old a. Swapping the order of the first two lines in the loop would give wrong results.
    • The result stays in 32 bits. Every bitwise result is a signed 32-bit integer, so the method is exact for 32-bit values. For example getSum(2147483647, 1) returns -2147483648, the same wrap-around a 32-bit int would show, but that is far outside this lesson's range.
    • Parameters are reassigned. a and b are local variables, so the loop can overwrite them without affecting the caller.
    • Types are erased. number doesn't promise integers. The bitwise operators would truncate a value like 1.5 to 1.

    Complexity

    Time: O(1). Each round pushes the lowest carry at least one place to the left, and after at most 32 rounds the carries are gone. Each round does a fixed number of operations.

    Space: O(1). The method keeps carry and reuses its two parameters.

    Edge cases and common mistakes

    • Zeros. getSum(0, 0) returns 0, and getSum(7, 0) skips the loop and returns 7.
    • Opposite numbers. getSum(-1, 1) and getSum(7, -7) both return 0: the carries run off the left end of the 32 bits.
    • Both negative. getSum(-1000, -1000) returns -2000, and getSum(1000, 1000) returns 2000.
    • Shifting the wrong value. The carry is (a & b) << 1. Without the shift, the carry would be added back into the same column and the loop would never finish.
    • Using | instead of ^. OR gives 1 for 1 + 1, which is wrong: the digit must be 0, with the carry going left.
    • Parentheses. a & b << 1 would shift b first, because << binds tighter than &. Keep the parentheses around a & b.

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