371. Sum of Two Integers
Input: a = 1, b = 2
Output: 3Input: a = -2, b = 3
Output: 1// Iteration
int getSum(int a, int b) { // time: O(1); space: O(1)
while (b) {
int carry = ((a & b) & 0x7fffffff) << 1;
a = a ^ b; // the first bit cannot be 1; otherwise, it cannot be left-shifted
b = carry;
}
return a;
}// Recursion
int getSum(int a, int b) { // time: O(1); space: O(1)
return b == 0 ? a : getSum(a ^ b, ((a & b) & 0x7fffffff) << 1);
}Last updated