Start learning free

LESSON 594 OF 673 · BIT MANIPULATION

Sum of Two Integers in Python: Bitwise Addition with a 32-bit Mask

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

    PYTHON · BIT MANIPULATION

    Sum Of Two Integers in Python, explained

    Problem overview

    The method getSum receives two integers, a and b, and returns their sum without using the operators + and -. Both are between -1000 and 1000, and they can be negative.

    For a = 1 and b = 2 the result is 3. For a = 2 and b = 3 it is 5. For a = -5 and b = 3 it is -2.

    The lesson asks for bitwise operations, O(1) time (a loop of at most one turn per bit of a 32-bit integer) and O(1) extra space.

    Approach: add column by column, as on paper

    Add two binary numbers one column at a time. In one column, 0 + 0 = 0, 0 + 1 = 1, and 1 + 1 = 10: a 0 stays in the column and a 1 is carried into the next column to the left. Two facts follow:

    • The digit left in each column is the XOR of the two bits, so a ^ b is the sum with the carries left out.
    • A carry appears only in a column where both bits are 1, so the carries are (a & b) << 1: the AND finds those columns and the shift moves each carry one column to the left.

    The two numbers a ^ b and (a & b) << 1 still add up to the original sum, so repeat the process with them. Each round, the carries move at least one column to the left. Once there are no carries left, the XOR part is the full answer.

    For 2 + 3 (010 and 011): the XOR is 001 and the carry is 100. The next round XORs those to 101 with no carry left. The sum is 101, which is 5.

    Why Python needs a mask

    This works directly in languages where an int has 32 bits. Python's integers have no fixed size, and a negative number behaves as if it had endless 1 bits on the left. Carries then never fall off the left end. For a = -1 and b = 1 without any mask, (a, b) goes (-2, 2), (-4, 4), (-8, 8), and so on, and b never reaches 0.

    The fix is to work on the lowest 32 bits only. The value 0xFFFFFFFF is 32 one bits, and x & mask keeps the lowest 32 bits of x. A carry that moves past bit 31 is cut off, as it would be in a 32-bit int, so after at most 32 rounds b is 0.

    The price is the end of the loop. The result in a is now a number between 0 and 4294967295 whose bit 31 may be set, which stands for a negative number in two's complement. The last step turns it back into a negative Python integer.

    Step by step

    1. Define the mask. Store 0xFFFFFFFF in mask. The prefix 0x starts a hexadecimal number, and each F is four 1 bits.
    2. Loop while b != 0. Here a holds the sum so far and b the carries still to add. When no carries remain, the sum is all in a.
    3. Compute the carries. carry = ((a & b) << 1) & mask: the columns where both bits are 1, moved one place left, then cut to 32 bits.
    4. Add without carries. a = (a ^ b) & mask.
    5. Feed the carries back. b = carry, so the next round adds them in. Compute carry before changing a, because it needs the old a.
    6. Handle a negative result. After the loop, if a > 0x7FFFFFFF, bit 31 is set, which means a negative number in a 32-bit int. Return ~(a ^ mask).
    7. Otherwise return a. Its top bit is 0, so it is already the right number.

    The solution in Python

    class Solution:
        def getSum(self, a: int, b: int) -> int:
            mask = 0xFFFFFFFF
            while b != 0:
                carry = ((a & b) << 1) & mask
                a = (a ^ b) & mask
                b = carry
            if a > 0x7FFFFFFF:
                return ~(a ^ mask)
            return a
    

    Python details worth knowing

    • The negative conversion. a ^ mask flips the 32 low bits of a. The ~ operator then flips every bit, including the infinite run above bit 31, which turns them into 1s. The result is the negative number those 32 bits stand for. For a = 0xFFFFFFFE, a ^ mask is 1, and ~1 is -2.
    • Negative inputs are fine. a & mask on a negative number gives its 32-bit two's complement form: -5 & 0xFFFFFFFF is 4294967291, which is 0xFFFFFFFB.
    • Python has no 32-bit overflow, so the mask is what imitates it. Results outside the 32-bit signed range wrap: getSum(2147483647, 1) returns -2147483648. The lesson's inputs stay within -1000 to 1000, so this never happens there.
    • Hexadecimal literals. 0x7FFFFFFF is 2147483647, the largest 32-bit signed value.

    Trace on a = -5, b = 3

    Running the solution, a and b hold these values after each round of the loop:

    Roundab
    10xfffffff80x00000006
    20xfffffffe0x00000000

    The loop ends with a = 0xFFFFFFFE. That is above 0x7FFFFFFF, so the method returns ~(a ^ mask), which is -2.

    Complexity

    Time: each round moves the lowest carry at least one place to the left, and the mask cuts off anything beyond 32 bits, so the loop runs at most 32 times, whatever the input. That is O(1). For -1 and 1 it uses all 32 rounds.

    Space: a few numbers are kept, so the extra space is O(1).

    Edge cases and common mistakes

    • Both zero. b is 0 at the start, the loop never runs, and the method returns 0.
    • Opposite numbers. For a = -1 and b = 1, the carry travels all the way up and falls off bit 31, leaving a = 0. The result is 0.
    • Two negatives. For a = -7 and b = -8 the result is -15.
    • Leaving out the mask. With a negative input, the loop doesn't end, as shown above.
    • Returning a unchanged at the end. For a negative sum this returns a large positive number such as 4294967294 instead of -2.
    • Updating a before computing carry. The carry must come from the old a and b; changing a first gives wrong carries.

    Testing

    These results come from running the solution:

    abResult
    123
    235
    -53-2
    000
    -110
    -7-8-15
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free