15% off all plans & roadmaps Use code
See plansSum of Two Integers
- LeetCode 371
- Medium
- Bit Manipulation Patterns
- Bitwise XOR - Finding Single/Missing Number
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.
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.
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
- Set
resulttoaandremainingtob. - While
remainingis not zero, check its sign. - If
remainingis positive, increaseresultby one and decreaseremainingby one. - If
remainingis negative, decreaseresultby one and increaseremainingby one. - Return
result.
Dry run
Use a = -1000 and b = -1000.
remainingis -1000, which is negative, so every round movesresultdown by one andremainingup by one.- After round 1,
resultis -1001 andremainingis -999. - After round 500,
resultis -1500 andremainingis -500. - After round 1000,
resultis -2000 andremainingis 0, so the loop stops.
The function returns -2000, which matches the expected output.
Complexity
| Time | O(|b|) |
|---|---|
| Space | O(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
JavaTested in our runner
class Solution {
public int getSum(int a, int b) {
int result = a;
int remaining = b;
while (remaining != 0) {
if (remaining > 0) {
result++;
remaining--;
} else {
result--;
remaining++;
}
}
return result;
}
}
C++Tested in our runner
class Solution {
public:
int getSum(int a, int b) {
int result = a;
int remaining = b;
while (remaining != 0) {
if (remaining > 0) {
result++;
remaining--;
} else {
result--;
remaining++;
}
}
return result;
}
};
JavaScriptTested in our runner
var getSum = function(a, b) {
let result = a;
let remaining = b;
while (remaining !== 0) {
if (remaining > 0) {
result++;
remaining--;
} else {
result--;
remaining++;
}
}
return result;
};
GoTested in our runner
func getSum(a int, b int) int {
result := a
remaining := b
for remaining != 0 {
if remaining > 0 {
result++
remaining--
} else {
result--
remaining++
}
}
return result
}
C#Tested in our runner
public class Solution {
public int getSum(int a, int b) {
int result = a;
int remaining = b;
while (remaining != 0) {
if (remaining > 0) {
result++;
remaining--;
} else {
result--;
remaining++;
}
}
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
- Treat
aandbas 32-bit patterns (mask them in Python). - Set
resultandcarryto 0, and start withbit = 1, the lowest column. - For each column, extract
x = a & bit,y = b & bitandc = carry & bit. - OR
x ^ y ^ cintoresultto write the sum bit. - Set
carryto((x & y) | (x & c) | (y & c)) << 1so it lands on the next column. - Shift
bitleft and stop after the top column (bit 31). - Convert the 32-bit
resultback 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
| Time | O(1) |
|---|---|
| Space | O(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)
JavaTested in our runner
import java.util.*;
class Solution {
public int getSum(int a, int b) {
int result = 0;
int carry = 0;
// bit walks through columns 0..31 and becomes 0 after the top column
for (int bit = 1; bit != 0; bit <<= 1) {
int x = a & bit;
int y = b & bit;
int c = carry & bit;
result |= x ^ y ^ c;
carry = ((x & y) | (x & c) | (y & c)) << 1;
}
return result;
}
}
C++Tested in our runner
class Solution {
public:
int getSum(int a, int b) {
unsigned int ua = static_cast<unsigned int>(a);
unsigned int ub = static_cast<unsigned int>(b);
unsigned int result = 0;
unsigned int carry = 0;
for (unsigned int bit = 1u; bit != 0u; bit <<= 1) {
unsigned int x = ua & bit;
unsigned int y = ub & bit;
unsigned int c = carry & bit;
result |= x ^ y ^ c;
carry = ((x & y) | (x & c) | (y & c)) << 1;
}
return static_cast<int>(result);
}
};
JavaScriptTested in our runner
var getSum = function(a, b) {
let result = 0;
let carry = 0;
// JS bitwise ops work on 32-bit ints, so bit becomes 0 after column 31
for (let bit = 1; bit !== 0; bit <<= 1) {
const x = a & bit;
const y = b & bit;
const c = carry & bit;
result |= x ^ y ^ c;
carry = ((x & y) | (x & c) | (y & c)) << 1;
}
return result;
};
GoTested in our runner
func getSum(a int, b int) int {
ua := uint32(a)
ub := uint32(b)
var result uint32 = 0
var carry uint32 = 0
for bit := uint32(1); bit != 0; bit <<= 1 {
x := ua & bit
y := ub & bit
c := carry & bit
result |= x ^ y ^ c
carry = ((x & y) | (x & c) | (y & c)) << 1
}
return int(int32(result))
}
C#Tested in our runner
public class Solution {
public int getSum(int a, int b) {
int result = 0;
int carry = 0;
for (int bit = 1; bit != 0; bit <<= 1) {
int x = a & bit;
int y = b & bit;
int c = carry & bit;
result |= x ^ y ^ c;
carry = ((x & y) | (x & c) | (y & c)) << 1;
}
return result;
}
}

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
- Treat
aandbas 32-bit patterns (mask them in Python, use unsigned or int32 types elsewhere). - Loop while
bis not zero. - Compute
carry = (a & b) << 1, the columns that overflow into their left neighbour. - Set
a = a ^ b, the sum without carries. - Set
b = carryand mask to 32 bits in Python. - When
bis zero,aholds the answer as a 32-bit pattern. - 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.
| Round | a (hex) | b (hex) | a & b | carry = (a & b) << 1 | a ^ b |
|---|---|---|---|---|---|
| 1 | 0xFFFFFC18 | 0xFFFFFC18 | 0xFFFFFC18 | 0xFFFFF830 | 0x00000000 |
| 2 | 0x00000000 | 0xFFFFF830 | 0x00000000 | 0x00000000 | 0xFFFFF830 |
| 3 | 0xFFFFF830 | 0x00000000 | loop 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
| Time | O(1) |
|---|---|
| Space | O(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)
JavaTested in our runner
import java.util.*;
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1; // int is 32 bits, so the top carry drops off
a = a ^ b;
b = carry;
}
return a;
}
}
C++Tested in our runner
class Solution {
public:
int getSum(int a, int b) {
unsigned int x = static_cast<unsigned int>(a);
unsigned int y = static_cast<unsigned int>(b);
while (y != 0u) {
unsigned int carry = (x & y) << 1; // unsigned avoids signed shift problems
x = x ^ y;
y = carry;
}
return static_cast<int>(x);
}
};
JavaScriptTested in our runner
var getSum = function(a, b) {
// JS bitwise operators convert to 32-bit signed ints on every step
while (b !== 0) {
const carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
};
GoTested in our runner
func getSum(a int, b int) int {
x := int32(a)
y := int32(b)
for y != 0 {
carry := (x & y) << 1 // int32 wraps, so the top carry drops off
x ^= y
y = carry
}
return int(x)
}
C#Tested in our runner
public class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
Common mistakes
- Using
a | bfor the partial sum. OR gives 1 when both bits are 1, but binary addition writes 0 there and carries. Usea ^ band let(a & b) << 1carry 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 != 0never ends. Maska,band each new value with0xFFFFFFFF. - Returning the masked value directly in Python. For -2000 the loop ends with 0xFFFFF830, which is 4294965296 as a Python int. Check
a <= 0x7FFFFFFFand otherwise return~(a ^ mask). - Using signed shifts in C++. Left-shifting a negative
intis undefined behaviour in older standards. Cast tounsigned intfirst and cast the result back toint. - Slipping in
+or-somewhere, such asi + 1in a loop counter or-bto flip a sign. The problem forbids them, so usebit <<= 1for 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
bwith two's complement, which is~b + 1, and add. Use your own adder for that+ 1, so subtraction isgetSum(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
bby(a & b) << 1. Its set bits come from set bits of the oldb, 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 beforebis zero. - Can you write it recursively?
- Yes. If
b == 0returna, otherwise returngetSum(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
Related problems
- Single Number II · same technique: Bitwise XOR - Finding Single/Missing Number
- Single Number · same technique: Bitwise XOR - Finding Single/Missing Number
- Missing Number · same technique: Bitwise XOR - Finding Single/Missing Number
- Find the Difference · same technique: Bitwise XOR - Finding Single/Missing Number
- Pow(x, n) · same pattern: Bit Manipulation Patterns
- Bitwise AND of Numbers Range · same pattern: Bit Manipulation Patterns
- Minimum Array End · same pattern: Bit Manipulation Patterns
- Parallel Courses · same pattern: Bit Manipulation Patterns
- Counting Bits · same pattern: Bit Manipulation Patterns
- Reverse Bits · same pattern: Bit Manipulation Patterns