15% off all plans & roadmaps Use code

See plans

Sum of Two Integers

Updated

TL;DR: Add two integers without using + or -. XOR gives the sum without carries, AND shifted left gives the carries, and you repeat until no carry is left.

Problem

Given two integers a and b, return their sum a + b. You may not use the + or - operators. Use bitwise operations to reproduce binary addition and carry propagation.

Both values can be positive, negative or zero. The result must equal the true arithmetic sum.

Example 1

Input: a = 14, b = -6
Output: 8
Explanation: 14 plus -6 is 8, and you must reach it without the forbidden operators.

Example 2

Input: a = -23, b = 7
Output: -16
Explanation: The negative value has the larger magnitude, so the sum is negative.

Example 3

Input: a = 0, b = 19
Output: 19
Explanation: Adding zero leaves the other integer unchanged.

Constraints

  • -1000 <= a <= 1000
  • -1000 <= b <= 1000
  • The + operator must not be used.
  • The - operator must not be used.

Constraints that matter

  • The ban on + and - means you must rebuild addition from XOR, AND and shifts, the same gates a hardware adder uses.
  • Values can be negative, so you must reason in two's complement. The same bit trick works for negatives in fixed-width integers, with no case split on sign.
  • The range is only -1000 to 1000, so even a loop that steps one unit at a time finishes quickly. The interviewer still wants the bitwise answer, because the stepping loop uses the banned operators.
  • Results stay within -2000 to 2000, so a 32-bit int never overflows. The only width issue is Python, whose integers have no fixed width.

View on LeetCode

Hints

Hint 1

This is a bit manipulation problem.

Hint 2

Start from a and walk b units toward zero.

Solution

Intuition

This is a bit manipulation problem. Look at how you add two numbers by hand in binary. At each column you add two bits, write down one bit, and maybe carry one to the next column. Those two jobs map onto two bitwise operators.

Picture column addition on paper. The digits you write are XOR, and the carries you pass left are AND shifted left by one.

The written bit is 1 when exactly one input bit is 1. That is XOR. The carry is 1 only when both input bits are 1. That is AND. A carry belongs to the next column, so you shift it left by one position.

Do all columns at once. a ^ b is the sum with every carry ignored. (a & b) << 1 is the set of carries, already moved to the columns where they land. The true sum is the carry-free sum plus the carries, which is another addition of the same kind, so repeat the step on the new pair.

Each repeat pushes the carries further left. After at most 32 rounds in a 32-bit integer, they fall off the top and the carry value is 0.

Two's complement makes negatives work with no extra code, because the adder hardware never checks signs. The only trap is Python, where you must mask to 32 bits yourself.

Watch the pattern animation

Worked example

Input: a = -1000, b = -1000
Output: -2000
Explanation: In 32-bit two's complement, -1000 is 0xFFFFFC18. Adding it to itself gives 0xFFFFF830, which is the 32-bit pattern for -2000. The top carry falls off the end of the 32 bits, and the sign comes out right on its own.

Approach 1: Step one unit at a time

Start from a and walk b units toward zero. For each unit of b, move the result by one in the matching direction. This is the beginner solution because it counts instead of adding.

Be upfront about the catch. ++ and -- are the same as + 1 and - 1, so this breaks the rule of the problem. It runs and gives correct answers, but an interviewer will not accept it as the final answer. Treat it as the baseline that shows why you need bit operations.

Steps

  1. Set result to a and remaining to b.
  2. While remaining is not zero, check its sign.
  3. If remaining is positive, increase result by one and decrease remaining by one.
  4. If remaining is negative, decrease result by one and increase remaining by one.
  5. Return result.

Dry run

Use a = -1000 and b = -1000.

  • remaining is -1000, which is negative, so every round moves result down by one and remaining up by one.
  • After round 1, result is -1001 and remaining is -999.
  • After round 500, result is -1500 and remaining is -500.
  • After round 1000, result is -2000 and remaining is 0, so the loop stops.

The function returns -2000, which matches the expected output.

Complexity

TimeO(|b|)
SpaceO(1)

The loop moves remaining one step closer to zero each round, so it runs exactly |b| times. Here n is the magnitude of b, at most 1000 in this problem. Only two integer variables exist, so space is constant. The time grows with the value of b, not with its bit width, which is why it scales badly for large inputs.

PythonTested in our runner

class Solution:
    def getSum(self, a: int, b: int) -> int:
        result = a
        remaining = b
        while remaining != 0:
            if remaining > 0:
                result += 1
                remaining -= 1
            else:
                result -= 1
                remaining += 1
        return result

Approach 2: Bit-by-bit full adder

What's slow, and wrong, in the previous approach: it counts with the banned operators and its running time depends on the value of b. The insight that fixes it: addition has a fixed structure per bit position. A one-bit full adder takes three inputs (bit of a, bit of b, incoming carry) and produces a sum bit and an outgoing carry.

The sum bit is the XOR of the three inputs. The outgoing carry is 1 when at least two inputs are 1, the majority function. Walk through all 32 positions from low to high, build the result bit by bit, and move the carry one position left each time. No + or - appears anywhere.

Steps

  1. Treat a and b as 32-bit patterns (mask them in Python).
  2. Set result and carry to 0, and start with bit = 1, the lowest column.
  3. For each column, extract x = a & bit, y = b & bit and c = carry & bit.
  4. OR x ^ y ^ c into result to write the sum bit.
  5. Set carry to ((x & y) | (x & c) | (y & c)) << 1 so it lands on the next column.
  6. Shift bit left and stop after the top column (bit 31).
  7. Convert the 32-bit result back to a signed integer and return it.

Dry run

Use a = -1000 and b = -1000, both 0xFFFFFC18. In binary the low byte is 00011000, bits 10 and 11 are set, and bits 12 to 31 are set.

  • Bits 0 to 2: both inputs 0, no carry, sum bits 0.
  • Bit 3: 1 + 1 gives sum 0, carry into bit 4.
  • Bit 4: 1 + 1 + carry 1 gives sum 1, carry into bit 5.
  • Bit 5: 0 + 0 + carry 1 gives sum 1, no carry.
  • Bits 6 to 9: all zero, sum bits 0.
  • Bit 10: 1 + 1 gives sum 0, carry into bit 11.
  • Bits 11 to 31: 1 + 1 + carry 1 gives sum 1 and carry 1 each time. The carry out of bit 31 drops off.

The set bits are 4, 5 and 11 to 31, which is 0xFFFFF830. As a signed 32-bit value that is -2000.

Complexity

TimeO(1)
SpaceO(1)

The loop visits each of the 32 bit positions exactly once, and each visit does a fixed number of bit operations. The work does not depend on the values, only on the integer width, so time is O(1). Here n is the bit width, 32. The code keeps a handful of integer variables, so space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def getSum(self, a: int, b: int) -> int:
        mask = 0xFFFFFFFF
        a &= mask
        b &= mask
        result = 0
        carry = 0
        bit = 1
        while bit <= mask:
            x = a & bit
            y = b & bit
            c = carry & bit
            result |= x ^ y ^ c  # sum bit of the full adder
            carry = ((x & y) | (x & c) | (y & c)) << 1  # majority, moved up one column
            bit <<= 1
        # bit 31 set means a negative two's-complement value
        return result if result <= 0x7FFFFFFF else ~(result ^ mask)
Bitwise XOR - Finding Single/Missing Number pattern infographic for Sum of Two Integers

Solution pattern

Bitwise XOR - Finding Single/Missing Number

Part of Bit Manipulation Patterns

Approach 3: XOR and carry loopOptimalBitwise XOR - Finding Single/Missing Number

What's slow in the previous approach: it processes all 32 columns one at a time, even when the carries die out after two or three rounds. It also needs a three-input adder per column. The insight that fixes it: process every column in parallel with two word-wide operations, then repeat only while a carry is left.

a ^ b is the sum of all columns with carries ignored. (a & b) << 1 is every carry, already placed in the column where it must be added. The true answer is the sum of those two values, so replace (a, b) with (a ^ b, (a & b) << 1) and repeat. When the second value is 0, the first one is the answer.

Termination is guaranteed. The lowest set bit of the carry value rises by at least one position each round, because carries come from bits that were set in the old carry value and then get shifted left. After at most 32 rounds, nothing is left in a 32-bit word.

Steps

  1. Treat a and b as 32-bit patterns (mask them in Python, use unsigned or int32 types elsewhere).
  2. Loop while b is not zero.
  3. Compute carry = (a & b) << 1, the columns that overflow into their left neighbour.
  4. Set a = a ^ b, the sum without carries.
  5. Set b = carry and mask to 32 bits in Python.
  6. When b is zero, a holds the answer as a 32-bit pattern.
  7. Convert the pattern to a signed integer (a no-op in Java, C#, JavaScript and Go, a cast in C++, a bit flip in Python) and return it.

Dry run

Use a = -1000 and b = -1000. Both start as 0xFFFFFC18. The table shows the state at the start of each round, and the carry computed in that round.

Rounda (hex)b (hex)a & bcarry = (a & b) << 1a ^ b
10xFFFFFC180xFFFFFC180xFFFFFC180xFFFFF8300x00000000
20x000000000xFFFFF8300x000000000x000000000xFFFFF830
30xFFFFF8300x00000000loop exits

In round 1, the AND is the whole value because both inputs are equal. Shifting it left by one doubles it and drops the top bit, giving 0xFFFFF830. The XOR is 0 because equal bits cancel.

In round 2, a is 0, so the AND is 0 and the carry is 0. The XOR moves 0xFFFFF830 into a. Now b is 0 and the loop stops. As a signed 32-bit value, 0xFFFFF830 is -2000, which matches the expected output.

Complexity

TimeO(1)
SpaceO(1)

Let n be the bit width, 32. The lowest set bit of b moves up by at least one column every round, since a & b is a subset of the old b and the shift adds one more. After at most 32 rounds b is 0, and each round does a constant number of word operations, so time is O(1), or O(n) in the bit width. The loop keeps only a, b and one temporary carry, so space is O(1).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def getSum(self, a: int, b: int) -> int:
        mask = 0xFFFFFFFF
        a &= mask
        b &= mask
        while b != 0:
            carry = ((a & b) << 1) & mask  # columns that overflow, moved left
            a = (a ^ b) & mask             # sum without carries
            b = carry
        # if bit 31 is set, rebuild the negative value
        return a if a <= 0x7FFFFFFF else ~(a ^ mask)

Common mistakes

  • Using a | b for the partial sum. OR gives 1 when both bits are 1, but binary addition writes 0 there and carries. Use a ^ b and let (a & b) << 1 carry the overlap.
  • Forgetting the shift and writing carry = a & b. The carry from column k must be added at column k + 1, so the shift by one is part of the definition.
  • Skipping the 32-bit mask in Python. Python integers have no fixed width, so a negative carry keeps sign-extending and the loop while b != 0 never ends. Mask a, b and each new value with 0xFFFFFFFF.
  • Returning the masked value directly in Python. For -2000 the loop ends with 0xFFFFF830, which is 4294965296 as a Python int. Check a <= 0x7FFFFFFF and otherwise return ~(a ^ mask).
  • Using signed shifts in C++. Left-shifting a negative int is undefined behaviour in older standards. Cast to unsigned int first and cast the result back to int.
  • Slipping in + or - somewhere, such as i + 1 in a loop counter or -b to flip a sign. The problem forbids them, so use bit <<= 1 for counters and bit tricks for everything else.

Edge cases

  • a = 0, b = 19: the first round has a & b = 0, the carry is 0, and the loop ends with 19.
  • a = 5, b = -5: the result must be 0. The carry chain runs through all 32 columns and drops off the top, leaving 0.
  • a = -1000, b = -1000: the most negative sum in range. Expect -2000, and in Python the final sign conversion is what makes it correct.
  • a = 1000, b = 1000: two positive values with the carry rippling upward. Expect 2000.
  • a = -1, b = 1: all 32 bits of the carry ripple from column 0 to column 31, then fall off. Expect 0.
  • a = -23, b = 7: opposite signs with the negative value larger in magnitude. Expect -16.

Follow-ups interviewers ask

How would you subtract two integers without - ?
Negate b with two's complement, which is ~b + 1, and add. Use your own adder for that + 1, so subtraction is getSum(a, getSum(~b, 1)). This works because two's complement turns subtraction into addition of the negated value.
Why does the loop always terminate, and how many rounds can it take?
Each round replaces b by (a & b) << 1. Its set bits come from set bits of the old b, shifted up one, so the lowest set bit moves up at least one column per round. In a 32-bit word that means at most 32 rounds before b is zero.
Can you write it recursively?
Yes. If b == 0 return a, otherwise return getSum(a ^ b, (a & b) << 1). It has the same bounds as the loop, with recursion depth at most 32 in a fixed-width integer. In Python you still need the 32-bit mask on the arguments.

Sum of Two Integers FAQ

What is the time complexity of Sum of Two Integers?

The XOR and carry loop runs at most 32 rounds for 32-bit integers, and each round does a few constant-time bit operations. That is O(1) time, or O(w) where w is the bit width. Space is O(1) because it uses only a few integer variables.

Why use XOR and AND for Sum of Two Integers?

XOR is the sum bit of a column when carries are ignored, because it is 1 when exactly one input bit is 1. AND finds the columns where both bits are 1, which are exactly the columns that produce a carry. Shifting that result left puts each carry in the column it affects.

How do you solve Sum of Two Integers in Python?

Mask both inputs to 32 bits with 0xFFFFFFFF, run the XOR and carry loop with a mask after each update, then convert back to signed. If the result is above 0x7FFFFFFF, return ~(a ^ mask). Without the mask, negative numbers make the loop run forever.

How do you solve Sum of Two Integers in Java?

Java int is already 32 bits with two's-complement wraparound, so the loop needs no mask. Run carry = (a & b) << 1; a ^= b; b = carry; until b is 0 and return a. The carry out of bit 31 drops off, which is what you want.

Why does Sum of Two Integers work for negative numbers?

Two's complement stores negatives so that ordinary binary addition on the bit patterns gives the correct signed sum. The XOR and carry loop is binary addition, so it works unchanged. You only need to keep the width fixed at 32 bits.

Can Sum of Two Integers be solved in O(1) extra space?

Yes. The iterative loop keeps two integers and one temporary carry, with no arrays or recursion. The recursive version uses O(32) stack frames, which is still constant for a fixed integer width.

Asked at

See which companies ask this — Pro

Practise it