1. 程式人生 > >[leetcode]371. Sum of Two Integers

[leetcode]371. Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Example 1:

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

分析:

求兩數之和,且不能用+,-。可以用用異或算不帶進位的和,用與並左移1位來算進位,然後把兩者加起來即可。

class Solution {
public:
    int getSum(int a, int b) {
        if(b == 0)
            return a;
        int sum = a ^ b;
        int carry = (a & b) << 1;
        return getSum(sum , carry);
    }
};