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.
解法1:Iteration
XOR是一个不带进位的加法运算,进位的信息可以通过AND(与运算)再左移获得。可以有Recursion和Iteration两种写法
C++123456789101112public class Solution { public int getSum(int a, int b) { while (b != 0) { int c = a ^ b; int carry = (a & b) << 1; a = c; b = carry; } return a; }}
解法2:Recursion
C++1234567891011public class Solution { public int getSum(int a, int b) { if (b == 0) { return a; // stop condition } int c = a ^ b; int carry = (a & b) << 1; return getSum(c, carry); }}