Given two integers a
and b
, return the sum of the two integers without using the operators +
and -
.
Example 1:
Input: a = 1, b = 2 Output: 3
Example 2:
Input: a = 2, b = 3 Output: 5
Constraints:
-1000 <= a, b <= 1000
Companies:
Facebook
Related Topics:
Bit Manipulation
Similar Questions:
// OJ: https://leetcode.com/problems/sum-of-two-integers/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
int getSum(int a, int b) {
int carry = 0, ans = 0;
for (int i = 0; i < 32; ++i) {
int x = (a >> i & 1), y = (b >> i & 1);
if (carry) {
if (x == y) {
ans |= 1 << i;
if (!x & !y) carry = 0;
}
} else {
if (x != y) ans |= 1 << i;
if (x & y) carry = 1;
}
}
return ans;
}
};
- Get
carry = (a & b) << 1
, i.e. the bits that are 1s both ina
andb
are picked and shifted left by 1. - As the
11
case is handled, the rest10
,01
,00
cases can be get usinga ^ b
. - Now the problem becomes calculating the sum of
(a & b) << 1
anda ^ b
. - Go back to step 1 until there is no more
carry
.
// OJ: https://leetcode.com/problems/sum-of-two-integers/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
int getSum(int a, int b) {
while (b) {
int carry = (a & b) << 1;
a ^= b;
b = carry;
}
return a;
}
};