Sum of Two Integers
Problem
Given two integers a and b, return the sum of the two integers without using the + and - operators.
Examples
Example 1:
Input: a = 1, b = 1
Output: 2
Example 2:
Input: a = 4, b = 7
Output: 11
Constraints
-1000 <= a, b <= 1000
You should aim for a solution with O(1) time and O(1) space.
Solution
Bit-wise adding.
class Solution {
public:
int getSum(int a, int b) {
int res = 0;
int carry = 0;
for (int i = 0; i < 32; ++i) {
int a_bit = (a >> i) & 1;
int b_bit = (b >> i) & 1;
int res_bit = a_bit ^ b_bit ^ carry;
carry = (a_bit + b_bit + carry) >= 2 ? 1 : 0;
res |= (res_bit << i);
}
// Limit to 32 bits
if (res > 0x7FFFFFFF) {
res = ~(res ^ 0x7FFFFFFF);
}
return res;
}
};