Lintcode位运算实现加法

其实我一开始是真不太会,还是看了大神的博客https://blog.csdn.net/qq_28444079/article/details/76849990才明白原理,感谢。

原理:二进制中个位数的加法可以通过x^y操作实现,而进位则需(x&y)<<1实现,此时进位后的值加上个位数加起来的值即为所求,那么也就是((x&y)<<1)^(x^y)

我的循环代码:

#include<iostream>
using namespace std;
int main()
{
	int a, b;
	cin >> a >> b;
	int add = a ^ b;    //个位数加法
	int carry = a & b;    //判断有无进位
	while (carry)       //当无进位说明加法结束,跳出循环
	{ 
		int tmp = add;
		carry <<= 1;
		add ^= carry;     //算出加法的和
		carry = tmp & carry;    //判断原来两个加数加了后有无进位
	}
	cout << add << endl;   //输出最终结果
	system("pause");
}

大神的递归代码:

public class Solution {

    public int aplusb(int a, int b) {
        // write your code here
        // a^b;//10^11=01没有进位
        // a&b //10&11=10 说明第2个数有进位,但是进位在高位(第3位)
        // <<1 //左移动一位 就是100
        // 最后把结果再进^操作给a,直到没有进位
          if (b == 0)//有1代表还有进位
            return a;
        else
            return aplusb(a^b, (a&b) << 1);
    }

猜你喜欢

转载自blog.csdn.net/weixin_44009743/article/details/89302350