[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);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/85198928
今日推荐