且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Sum of Two Integers 两数之和

更新时间:2022-09-16 09:03:30

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.

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

这道题是CareerCup上的一道原题,难道现在LeetCode的新题都是到处抄来的么,讲解可以参见我之前的博客18.1 Add Two Numbers。简而言之就是用异或算不带进位的和,用与并左移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);
    }
};

上面的解法可以精简到一行,哈哈,叼不叼?

解法二:

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

也可以写成迭代的样子,思路都是一样的~

解法三:

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

本文转自博客园Grandyang的博客,原文链接:两数之和[LeetCode] Sum of Two Integers ,如需转载请自行联系原博主。