Sum of Two Integers
Medium
Bit ManipulationMath
Problem
Return the sum of two integers a and b without using the + or - operators. Use bitwise tricks: XOR gives sum-without-carry, AND-then-shift gives the carry.
Example 1
Input: a = 1, b = 2
Output: 3
Example 2
Input: a = -1, b = 1
Output: 0
Example 3
Input: a = 5, b = -3
Output: 2
Constraints
- −1000 ≤ a, b ≤ 1000
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
Python
class Solution:
def getSum(self, a, b):
mask = 0xFFFFFFFF
while b & mask:
a, b = a ^ b, (a & b) << 1
a &= mask
return a if a <= 0x7FFFFFFF else ~(a ^ mask)
Java
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Sum of Two Integers interactively → ← All solutions