Iterative Bit Manipulation
Intuition
When we add two binary numbers, the sum without carrying is equivalent to XOR, and the carry is equivalent to AND shifted left by one. We can repeatedly compute the XOR (partial sum) and the carry until the carry becomes zero. At that point, the XOR result holds the final sum. This works because XOR captures the bit positions where only one bit is set, while AND captures positions where both bits are set and a carry is needed.
Algorithm
- Compute the XOR of `a` and `b` to get the partial sum (bits that differ).
- Compute the AND of `a` and `b`, then shift left by one to get the carry.
- Set `a` to the partial sum (XOR result) and `b` to the carry.
- Repeat steps 1-3 until the carry `b` becomes zero.
- Return `a` as the final result.
O(1) — at most 32 iterations for 32-bit integersSpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int getSum(int a, int b) {
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
};class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
}class Solution:
def getSum(self, a: int, b: int) -> int:
MASK = 0xFFFFFFFF
MAX_INT = 0x7FFFFFFF
a &= MASK
b &= MASK
while b != 0:
carry = (a & b) & MASK
a = (a ^ b) & MASK
b = (carry << 1) & MASK
return a if a <= MAX_INT else ~(a ^ MASK)func getSum(a int, b int) int {
for b != 0 {
carry := a & b
a = a ^ b
b = carry << 1
}
return a
}