1. 程式人生 > >[LeetCode] Sum of Two Integers 兩數之和

[LeetCode] Sum of Two Integers 兩數之和

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

參考資料: