首页 > 代码库 > 《Cracking the Coding Interview》——第18章:难题——题目1

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

2014-04-29 00:56

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

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

代码:

 1 // 18.1 add two numbers wihout using arithmetic operator.
 2 #include <iostream>
 3 using namespace std;
 4 
 5 int add(int x, int y)
 6 {
 7     int sum;
 8     int carry;
 9     int bx, by;
10     int base;
11     
12     base = 1;
13     carry = 0;
14     sum = 0;
15     while (base != 0) {
16         bx = x & base;
17         by = y & base;
18         base <<= 1;
19         sum |= ((bx) ^ (by) ^ carry);
20         carry = ((bx & by) || (bx & carry) || (by & carry)) ? base : 0;
21     }
22     
23     return sum;
24 }
25 
26 int main()
27 {
28     int x, y;
29     
30     while (cin >> x >> y) {
31         cout << add(x, y) << endl;
32     }
33     
34     return 0;
35 }