题目
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.
提示
位运算
解
public class Solution {
public int getSum(int a, int b) {
//循环更精简,省去内存中栈的使用
// while (b != 0) {
// int c = a ^ b;
// b = (a & b) << 1;
// a = c;
// }
// return a;
//递归可以清晰的看出来过程
if(b==0){
return a;
}
else{
return getSum(a^b,(a&b)<<1);
}
}
}
参考链接
1:http://bookshadow.com/weblog/2016/06/30/leetcode-sum-of-two-integers/?utm_source=tuicool&utm_medium=referral
2:http://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/