Sum of Two Integers
Problem
Given two integers a and b, return their sum **without using the operators + and -**.
Example 1
- Input
a = 1, b = 2- Output
3
Example 2
- Input
a = 2, b = 3- Output
5
Example 3
- Input
a = -1, b = 1- Output
0
Constraints
- -1000 ≤ a, b ≤ 1000
Explanation
Adding two bits gives a sum bit (a XOR b) and a carry (a AND b) that moves one place left. So a + b = (a ^ b) + ((a & b) << 1), which is again an addition, but with fewer carries each time. Repeat until there is no carry.
Java's 32-bit int wraps around naturally. Python integers are unbounded, so mask to 32 bits and convert back to a signed value at the end.
Approach 1 · Better
Bit-by-bit ripple adder
- Time O(32)
- Space O(1)
Add the numbers one bit position at a time, like a hardware full adder, carrying into the next position.
- For each of the 32 bit positions, take bit
iofaand ofb, and the carry. - The result bit is
x ^ y ^ carry; the new carry is(x & y) | (x & carry) | (y & carry).
class Solution {
public int getSum(int a, int b) {
int result = 0;
int carry = 0;
for (int i = 0; i < 32; i++) {
int x = (a >>> i) & 1;
int y = (b >>> i) & 1;
result |= (x ^ y ^ carry) << i;
carry = (x & y) | (x & carry) | (y & carry);
}
return result;
}
}class Solution:
def getSum(self, a: int, b: int) -> int:
result = carry = 0
for i in range(32):
x, y = (a >> i) & 1, (b >> i) & 1
result |= (x ^ y ^ carry) << i
carry = (x & y) | (x & carry) | (y & carry)
# Interpret the 32 bits as a signed integer.
return result if result < 1 << 31 else result - (1 << 32)Approach 2 · Optimal
XOR and carry loop
- Time O(32)
- Space O(1)
Repeatedly replace (a, b) with (a ^ b, (a & b) << 1) until the carry b is zero.
- While
b != 0:carry = (a & b) << 1;a = a ^ b;b = carry. - In Python, mask with
0xFFFFFFFFeach step and convert the result back to signed.
class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
}class Solution:
def getSum(self, a: int, b: int) -> int:
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)Complexity compared
| Approach | Time | Space |
|---|---|---|
| Better Bit-by-bit ripple adder | O(32) | O(1) |
| Optimal XOR and carry loop | O(32) | O(1) |
Key takeaways
- XOR is addition without carry; AND finds where carries happen.
- Python needs the 32-bit mask, or a negative number makes the loop run forever.
Your notes
Saved in this browser as you type.
Solved it on your own?
Mark it done to track your progress, or star it to come back before an interview.