And two integers LeetCode_371

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;
    }
}
Published 250 original articles · won praise 0 · Views 1087

Guess you like

Origin blog.csdn.net/qq_36198826/article/details/104034261