Wonder奇迹奇迹

导航

C++不用任何算术运算符实现整数加法

这本是careerup的一道题,看到了以后自己做了一下,主要的难点就是加法里面的进位。直接上代码:

 1 int  add(int a, int b)
 2 {
 3     const int bitsize = sizeof(int) * 8;
 4     int digit[bitsize] = {0};
 5     int first = a, second = b;
 6     int carry =0;
 7     int result = 0;
 8     for (int i = 0; i < bitsize; i++)
 9     {
10         
11         digit[i] = (first & 1) ^ (second & 1) ^ carry;
12 
13         if (((first & 1) == 1 && (second & 1) == 1) || ((first & 1) == 1 && carry == 1) || (carry == 1 && (second & 1) == 1))
14             carry = 1;
15         else
16             carry = 0;
17 
18         first = first >> 1;
19         second = second >> 1;
20 
21         result = result | (digit[i] << i);
22     }
23     return result;
24     
25 }

后来网上发现了一个更加简便的方法:

1 int add_no_arithm(int a, int b)
2 {
3     if (b == 0) return a;
4     int sum = a ^ b; // add without carrying
5     int carry = (a & b) << 1; // carry, but don’t add
6     return add_no_arithm(sum, carry); // recurse
7 }

真是巧妙啊,carry就是需要进位的地方。

posted on 2015-05-19 19:06  Wonder奇迹奇迹  阅读(658)  评论(0编辑  收藏  举报