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 }

 

相关文章:

  • 2021-06-16
  • 2021-08-22
  • 2021-12-27
  • 2021-08-10
  • 2021-11-29
  • 2021-11-21
  • 2021-10-25
  • 2022-02-17
猜你喜欢
  • 2021-06-19
  • 2021-10-19
  • 2021-09-10
  • 2021-09-21
  • 2021-10-23
  • 2021-10-10
  • 2021-12-17
相关资源
相似解决方案