LintCode-A + B 用位操作模拟加法

时间:2022-05-29 14:29:32
class Solution {
public:
/*
* @param a: The first integer
* @param b: The second integer
* @return: The sum of a and b
*/
int aplusb(int a, int b) {
// write your code here, try to do it without arithmetic operators.
if(a==)return b;
if(b==)return a;
int x1 = a^b;
int x2 = (a&b)<<;
return aplusb(x1,x2);
}
};

俩位相加有四种情况:

1. 1 + 1 = 10;

2. 1 + 0 = 01;

3. 0 + 1 = 01;

4. 0 + 0 = 00;

第一种情况,即有进位,用 (a&b)<<1解决;

第二第三种情况,用a^b解决。