Algo-Sim › Matrix & Bit Manipulation
Sum of Two Integers
Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input
Add two integers without + or −: XOR adds without carries, AND shifted left gives the carries; repeat until no carry is left.
Problem
Given two integers a and b, return their sum without using the + or - operators.
Constraints
- -1000 ≤ a, b ≤ 1000
- Negative values use two's complement, so the carry loop must handle them
Edge cases to test
- Negative numbers
- One operand 0
- A carry that ripples through every bit:
-1 + 1
Follow-up questions
- Why does it loop forever in Python?
- Python ints are unbounded, so a negative carry never shifts out. Mask with
0xFFFFFFFFeach round and convert back to signed at the end. - How many iterations can it take?
- At most 32: each round moves the carry at least one bit left.
Solution
Java
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a ^= b;
b = carry;
}
return a;
}Python
def get_sum(a, b):
mask = 0xFFFFFFFF
a, b = a & mask, b & mask
while b != 0:
carry = ((a & b) << 1) & mask
a, b = a ^ b, carry
return a if a <= 0x7FFFFFFF else ~(a ^ mask)C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int getSum(int a, int b) {
uint32_t x = uint32_t(a), y = uint32_t(b);
while (y != 0) {
uint32_t carry = (x & y) << 1;
x ^= y;
y = carry;
}
return int32_t(x);
}
};
More Matrix & Bit Manipulation problems
- Rotate Image (Medium)
- Spiral Matrix (Medium)
- Set Matrix Zeroes (Medium)
- Search a 2D Matrix (Medium)
- Search a 2D Matrix II (Medium)
- Valid Sudoku (Medium)
- Single Number (Easy)
- Single Number II (Medium)
- Single Number III (Medium)
- Number of 1 Bits (Easy)
- Counting Bits (Easy)
- Reverse Bits (Easy)
- Missing Number (Easy)
- Power of Two (Easy)