LintCode-A + B 问题

给出两个整数a和b, 求他们的和, 但不能使用 + 等数学运算符。

您在真实的面试中是否遇到过这个题? 
Yes
例子

假设 a=1 而且 b=2。返回3

注意

你不须要从输入流读入数据,仅仅须要依据aplusb的两个參数a和b,计算他们的和并返回即可。

挑战

显然你能够直接 return a + b,可是你能否够挑战一下不这样做?

说明

a和b都是 32位 整数么?

  • 是的

我能够使用位运算符么?

  • 当然能够
标签 Expand  


分析:用位操作异或和与来模拟进位

代码:

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==0)return b;
        if(b==0)return a;
        int x1 = a^b;
        int x2 = (a&b)<<1;
        return aplusb(x1,x2);
    }
};


原文地址:https://www.cnblogs.com/wzzkaifa/p/6932266.html