一、递归解法:
#include<iostream>
using namespace std;
int add(int x, int y)
{
int a = x^y;
int b = (x&y)<<1;
if (b == 0)
{
return a;
}
return add(a, b);
}
int main()
{
int x, y;
while (cin >> x >> y) {
cout << add(x, y) << endl;
}
system("pause");
return 0;
}
二、循环解法:
#include <iostream>
using namespace std;
int add1(int x, int y)
{
int sum;
int carry;
int bx, by;
int base;
base = 1;
carry = 0;
sum = 0;
while (base != 0) {
bx = x & base;
by = y & base;
base <<= 1;
sum |= ((bx) ^ (by) ^ carry);
carry = ((bx & by) || (bx & carry) || (by & carry)) ? base : 0;
}
return sum;
}