Sum of Two Integers
Medium · Bit manipulation
Jump to codeCompute the sum of two signed 32-bit integers without using addition or subtraction operators. Use 32-bit two’s-complement wraparound if overflow occurs.
Examples
Example 1
a = 1 b = 2
Output: 3
Example 2
a = 2 b = 3
Output: 5
Constraints
- -1000 <= a, b <= 1000
Need a hint?
XOR adds without carry; AND identifies the carry positions.
Real bit manipulation interview questions
Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.
- Maximize the Bitwise AND of K Elements After Spending an Increment BudgetAmazon
- Implement IPv4 iterators and CIDR expansionOpenAI
- Implement firewall matching with CIDR rulesDatabricks
Solution approach
Repeatedly compute the carry as (a & b) shifted left and the carry-free sum as a XOR b, assigning both from the old operands. Mask each intermediate to 32 bits. Stop when carry is zero, then interpret the result as signed. The mask prevents negative integers from creating an infinite carry in unbounded-integer languages.
Complexity
At most 32 carry iterations and O(1) space for fixed-width integers.
Python reference solution
def getSum(a, b):
mask = 0xffffffff
a, b = a & mask, b & mask
while b:
a, b = (a ^ b) & mask, ((a & b) << 1) & mask
return a if a <= 0x7fffffff else ~(a ^ mask)
JavaScript solution
function getSum(a, b) {
while (b !== 0) {
const carry = (a & b) << 1;
a ^= b;
b = carry;
}
return a;
}
Java solution
import java.util.*;
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a ^= b;
b = carry;
}
return a;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getSum(int a, int b) {
// Unsigned shifts avoid undefined behavior when an operand is negative.
uint32_t x = static_cast<uint32_t>(a), y = static_cast<uint32_t>(b);
while (y != 0) {
uint32_t carry = (x & y) << 1;
x ^= y;
y = carry;
}
// Convert the 32-bit two's-complement result without an out-of-range cast.
return x <= INT_MAX ? static_cast<int>(x) : -1 - static_cast<int>(~x);
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ 1, 2 ]
3
[ 2, 3 ]
5
[ -1, 1 ]
0
[ -5, -7 ]
-12
[ 1000, -1000 ]
0
Drafts are saved per language in this browser when storage is available.