LeetCode刷题实战371:两整数之和
Given two integers a and b, return the sum of the two integers without using the operators + and -.
示例
输入: length = 5, updates = [[1,3,2],[2,4,3],[0,2,-2]]
输出: [-2,0,3,5,3]
解释:
初始状态:
[0,0,0,0,0]
进行了操作 [1,3,2] 后的状态:
[0,2,2,2,0]
进行了操作 [2,4,3] 后的状态:
[0,2,5,5,3]
进行了操作 [0,2,-2] 后的状态:
[-2,0,3,5,3]
解题
class Solution {
public:
int getSum(int a, int b) {
int result = a^b;
//判断是否需要进位
int forward = (a&b) <<1;
if(forward!=0){
//如有进位,则将二进制数左移一位,进行递归
return getSum(result,forward);
}
return result;
}
};
赞 (0)