Without using operators + and - calculates two integers a, b sum.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/sum-of-two-integers
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
class Solution {
public int getSum(int a, int b) {
//异或^ 得到无进位加法结果
//与& 得到进位加法结果,但是要向左移一位
//加法的结果为 ^与& 得到的结果之和
int sum = a^b;
int ci = (a&b)<<1;
if(ci!=0){
sum = getSum(sum,ci);
}
return sum;
}
}