LeetCode刷题实战371:两整数之和
Given two integers a and b, return the sum of the two integers without using the operators + and -.
示例
示例 1:
输入: a = 1, b = 2
输出: 3
示例 2:
输入: a = -2, b = 3
输出: 1
解题
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;
}
};
评论