码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Sum of Two Integers 两数之和

时间:2016-07-01 08:56:14      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

 

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

 

参考资料:

http://www.cnblogs.com/grandyang/p/5451942.html

https://leetcode.com/discuss/111682/one-line-java-code

https://leetcode.com/discuss/111601/6-line-java-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Sum of Two Integers 两数之和

标签:

原文地址:http://www.cnblogs.com/grandyang/p/5631814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!