371. Sum of Two Integers

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、能用a^b来得到两数和不需要进位的位。  //^异或(XOR)

2、能用a&b来得到两数和需要进位的位,(a&b)<<1+a^b就是Sum。

3、把(a&b)<<1和a^b作为参数,递归调用getSum,直到参数a等于零,返回两数和。

1 class Solution {
2 public:
3     int getSum(int a, int b) {
4         if(a==0)return b;
5         return getSum((a&b)<<1,a^b);
6     }
7 };    
原文地址:https://www.cnblogs.com/Z-Sky/p/5646532.html