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