0%

sum-of-two-integers

Sum of Two Integers – LeetCode 371

Problem

Description

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example

Given a = 1 and b = 2, return 3.

Answer

Original

Code

1
2
3
4
5
6
class Solution {
public:
int getSum(int a, int b) {
return b == 0 ? a : getSum(a ^ b, (a & b) << 1);
}
};

思路

优先计算xor得到未进位和,然后在and之后<<1得到进位后的结果,之后再相加,使用递归。
耗时$2$ ms,排名$84.71\%$

Better

思路

还没看到更好的思路。