[Jobdu] 题目1507:不用加减乘除做加法

题目描述:

写一个函数,求两个整数之和,要求在函数体内不得使用+、-、*、/四则运算符号。

输入:

输入可能包含多个测试样例。
对于每个测试案例,输入为两个整数m和n(1<=m,n<=1000000)。

输出:

对应每个测试案例,输出m+n的值。

样例输入:
3 4
7 9
样例输出:
7
16

不用+、-、*、/ 那只能使用二进制了,使用异或^得到不带进位的结果,使用&得到进位,重复操作直至没有进位。

 1 #include <cstdio>
 2  
 3 int add(int a, int b) {
 4     int n1, n2;
 5     do {
 6         n1 = a ^ b;
 7         n2 = (a & b) << 1;
 8          
 9         a = n1;
10         b = n2;
11     } while (n2 != 0);
12  
13     return n1;
14 }
15  
16 int main() {
17     int a, b;
18     while (scanf("%d %d", &a, &b) != EOF) {
19         printf("%d
", add(a, b));
20     }
21     return 0;
22 }
23  
24 /**************************************************************
25     Problem: 1507
26     User: hupo250
27     Language: C++
28     Result: Accepted
29     Time:10 ms
30     Memory:1020 kb
31 ****************************************************************/
原文地址:https://www.cnblogs.com/easonliu/p/4238634.html