[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 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.
这道题是CareerCup上的一道原题,难道现在LeetCode的新题都是到处抄来的么,讲解可以参见我之前的博客18.1 Add Two Numbers。简而言之就是用异或算不带进位的和,用与并左移1位来算进位,然后把两者加起来即可,先来看递归的写法如下:
a ^ b 表示没有考虑进位的情况下两数的和,(a & b) << 1 就是进位。
递归会终止的原因是 (a & b) << 1 最右边会多一个 0,那么继续递归,进位最右边的 0 会慢慢增多,最后进位会变为 0,递归终止。
class Solution {
public int getSum(int a, int b) {
if(b == 0)
return a;
int sum = a ^ b;
int jinwei = (a & b) << 1;
return getSum(sum, jinwei);
}
}