Sum of Two Integers (LeetCode 371): Solution and Explanation
Given two integers a and b, compute their sum without using the plus or minus operators. The only tools are bitwise operations, and the result must behave like ordinary 32-bit signed addition, including negative numbers.
Watch it run step by step
Try your own input and write the code →Intuition
Think about how you add two binary numbers on paper. In each column, the result bit is 1 when exactly one input bit is 1, and a carry goes into the next column when both are 1. Those two rules map directly to bitwise operators: a ^ b gives the sum of every column while ignoring carries, and (a & b) << 1 gives all the carries, already shifted into the column they belong to.
So one addition becomes two numbers: the partial sum and the carry. Adding those two is the same problem again, which is why the code loops. Each round, the carry has to move at least one position to the left, so after at most 32 rounds it either becomes zero or slides off the end of a 32-bit word, and the partial sum is the answer.
The catch in Python is that integers have unlimited width. A negative number behaves as if it had infinitely many leading 1 bits, so a carry would keep shifting left forever. Masking every intermediate value with 0xFFFFFFFF pins everything to 32 bits, exactly like Java or C++ registers. At the end, a value above 0x7FFFFFFF has its sign bit set, so it is converted back to a negative Python integer with ~(a ^ MASK).
Approach: XOR sum with AND carry, masked to 32 bits
- Define
MASK = 0xFFFFFFFFto keep 32 bits andMAX = 0x7FFFFFFF, the largest positive 32-bit value. - Loop while
bis not zero;bholds the pending carry. - Compute the carry as
((a & b) << 1) & MASK, the columns where both numbers have a 1, moved one place left. - Compute the carry-free sum as
(a ^ b) & MASKand store it ina. - Move the carry into
band repeat, since adding the carry to the partial sum is the same problem. - When the carry is gone, return
adirectly if it is at mostMAX, otherwise return~(a ^ MASK)to reinterpret the 32-bit pattern as a negative number.
Step-by-step example
a = 2, b = 3
- In binary
a = 010andb = 011. Round 1:a & b = 010, shifted gives carry100(4).a ^ b = 001(1). Nowa = 1,b = 4. - Round 2:
1 & 4 = 0, so the carry is 0.1 ^ 4 = 101(5). Nowa = 5,b = 0. - The loop stops because
bis 0. Since 5 is not aboveMAX, the function returns 5. - For a negative case like
a = -2, b = 3, the masked value of-2is0xFFFFFFFE. The carry walks left one bit per round until it falls past bit 31 and is masked away, leavinga = 1, which is the correct sum.
Code: Python, Java, C++
1class Solution:
2 def getSum(self, a: int, b: int) -> int:
3 MASK = 0xFFFFFFFF
4 MAX = 0x7FFFFFFF
5
6 while b != 0:
7 carry = ((a & b) << 1) & MASK
8 a = (a ^ b) & MASK
9 b = carry
10
11 # Convert from unsigned to signed
12 return a if a <= MAX else ~(a ^ MASK)1class Solution {
2 public int getSum(int a, int b) {
3 while (b != 0) {
4 int carry = (a & b) << 1;
5 a = a ^ b;
6 b = carry;
7 }
8 return a;
9 }
10}1class Solution {
2public:
3 int getSum(int a, int b) {
4 while (b != 0) {
5 unsigned carry = (unsigned)(a & b) << 1;
6 a = a ^ b;
7 b = carry;
8 }
9 return a;
10 }
11};Time and space complexity
O(1)
The carry gains at least one trailing zero each round, so with a fixed 32-bit width the loop runs at most 32 times regardless of the input values.
O(1)
Only a handful of integer variables are used.
Other approaches
Recursive formulation (time O(1), space O(1) (bounded recursion depth of 32))
Return a when b is zero, otherwise recurse on (a ^ b) & MASK and ((a & b) << 1) & MASK. It is the same algorithm written as tail recursion and reads nicely, but it gains nothing over the loop.
Native wraparound in Java or C++ (time O(1), space O(1))
In languages with fixed-width ints you can drop the mask entirely, because overflow naturally discards the carry past bit 31. In C++ use unsigned arithmetic for the shift to avoid undefined behavior on negative values.
Common mistakes
- Skipping the mask in Python. With a negative input, the carry never becomes zero because Python integers have no top bit to fall off, so the loop runs forever.
- Returning the masked value directly.
0xFFFFFFFFis 4294967295 in Python, not -1, so you must convert values above0x7FFFFFFFback to negatives. - Shifting the carry before computing the AND, or shifting the XOR. Only the carry moves left; the partial sum stays where it is.
- Updating
abefore computing the carry from the olda. Both new values must come from the same old pair, so compute the carry first or use simultaneous assignment.
Frequently asked questions
How do you add two numbers without the plus operator?
Use XOR to add each bit column without carries and AND followed by a left shift to compute the carries. Repeat with the partial sum and the carry until the carry is zero.
Why does this loop forever in Python with negative numbers?
Python integers are arbitrary precision, so a negative number has infinitely many 1 bits and the carry never disappears. Masking every step with 0xFFFFFFFF simulates a 32-bit register and lets the carry fall off the top.
What does ~(a ^ MASK) do?
It converts a 32-bit unsigned pattern into a negative Python integer. XOR with the mask flips the low 32 bits, and ~ flips everything back while extending the sign, which yields the two's complement value.
What is the time complexity of sum of two integers?
Constant time. Each round pushes the carry at least one bit to the left, so on 32-bit values the loop runs at most 32 times.