1. 程式人生 > >【LeetCode】371. Sum of Two Integers

【LeetCode】371. Sum of Two Integers

Problem: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.

題目:計算a和b的和,不使用加減運算子。

思路:使用異或,與等邏輯運算。(參考計算機組成原理中補碼加減法等)

使用異或保留二進位制中的不同位,與運算保留相同位,左移則實現進位操作,再用異或運算實現相加,同時與運算左移實現進位,直至與運算後為0停止。

程式碼:

class Solution {
    public int getSum(int a, int b) {
        
        return (b==0)?a:getSum(a^b,(a&b)<<1);
        //return ((a&b)<<1)|(a^b);
    }
}