test cases all pass
0 ms
public int getSum(int a, int b) {
if(b == 0){//没有进为的时候完成运算
return a;
}
int sum,carry;
sum = a^b;//完成第一步加发的运算
carry = (a&b)<<1;//完成第二步进位并且左移运算
return getSum(sum,carry);//
}
Hah, my c++ solution has the same idea. The base case uses | operator, which may be easier to think of. But @lid004's code is more concise.
class Solution {
public:
int getSum(int a, int b) {
int base = a ^ b;
int carrier = (a & b) << 1;
//merge
//base case
if ((base & carrier) == 0) return base | carrier;
//recursive case
return getSum(base, carrier);
}
};
@johnjavabean I think python uses "unlimited" bits (not sure how many bits myself) to represent integer vs Java / Cpp uses fixed bit length for primitive types. So if you code Python in a Java / Cpp way, you won't hit the base case as expected.