您的位置:首页 > 其它

《Cracking the Coding Interview》——第18章:难题——题目1

2014-04-29 00:59 411 查看
2014-04-29 00:56

题目:不用算数运算,完成加法。

解法:那就位运算吧,用加法器的做法就可以了。

代码:

// 18.1 add two numbers wihout using arithmetic operator.
#include <iostream>
using namespace std;

int add(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;
}

int main()
{
int x, y;

while (cin >> x >> y) {
cout << add(x, y) << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: