Sum of Two Integers (no + or -)
Problem
Return a + b without using the + or − operators.
Example 1
Input: a = 1, b = 2 Output: 3
Example 2
Input: a = -2, b = 3 Output: 1
Test cases
Case 1
Input: 1, 2 Expected: 3
Case 2
Input: -2, 3 Expected: 1
Case 3
Input: -5, -7 Expected: -12
View solutionHide solution1 approach
1. XOR for sum, AND-shift for carry
Time O(32)Space O(1)
a ^ b adds without carrying; (a & b) << 1 is the carry. Repeat until there is no carry. JavaScript 32-bit ints make negatives work too.
function getSum(a, b) { while (b !== 0) { const carry = (a & b) << 1; a = a ^ b; b = carry; } return a;}