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

Input: a = 1, b = 2
Output: 3
Input: a = -2, b = 3
Output: 1

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    int getSum(int a, int b) {
        if(!b)
            return a;
        int Xor = a ^ b;
        int And = (a & b) << 1;
        return getSum(Xor,And);
    }
};

Result

371. Sum of Two Integers_第1张图片
371. Sum of Two Integers.png

你可能感兴趣的:(371. Sum of Two Integers)