Sum of Two Integers (Without + or -) Explained
Problem Statement
Given two integers a and b, compute their sum without using the addition (+) or subtraction (-) operators. This problem tests your understanding of bitwise operations, specifically XOR and AND, to simulate binary addition by handling bit sums and carries iteratively.
Example
Input: a = 2, b = 3
Output: 5
Explanation: The sum 2 + 3 is computed as 5 using bitwise operations.
Code
Java
Python
JavaScript
public class Solution {
public int getSum(int a, int b) {
while (b != 0) {
int carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.getSum(2, 3)); // 5
}
}
def get_sum(a, b):
mask = 0xffffffff
while (b & mask) > 0:
carry = ((a & b) << 1) & mask
a = (a ^ b) & mask
b = carry
if (a >> 31) & 1:
return ~(a ^ mask)
return a
# Example usage
print(get_sum(2, 3)) # 5
function getSum(a, b) {
while (b !== 0) {
let carry = (a & b) << 1;
a = a ^ b;
b = carry;
}
return a;
}
// Example usage
console.log(getSum(2, 3)); // 5
Explanation
- Use XOR (
a ^ b) to compute the sum of bits without considering carries. - Use AND and left-shift (
(a & b) << 1) to compute the carry bits. - Update
ato the sum without carry andbto the carry. - Repeat until there are no more carries (
b == 0). - Return
aas the final sum.
Note
The time complexity is O(log n), where n is the maximum number of bits in the inputs, due to carry propagation. Python requires a mask to handle unbounded integers and negative numbers correctly, ensuring 32-bit behavior.
