A + B Problem II 大数加法

题目描述:

Input

The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.

Output

For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.

Sample Input

2

1 2

112233445566778899 998877665544332211

Sample Output

Case 1:

1 + 2 = 3

Case 2:

112233445566778899 + 998877665544332211 = 1111111111111111110

代码如下:

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 string ans;
 5 void bintadd(string a,string b)
 6 {
 7     int alen = a.length() - 1,blen = b.length() - 1;//alen,blen分别存放a,b字符串的最大下标
 8     int up = 0,i = 0,j,te;//up存放进位值,te存放余数
 9 
10     while(alen >= 0 || blen >= 0)
11     {
12         if(alen >= 0 && blen >= 0)//两个字符串都没有计算完
13             te = a[alen--] + b[blen--] + up -'0' - '0';//倒着计算字符串里的数,记得要加上进位值up
14         else
15             if(alen >= 0 && blen < 0)//如果b字符串已经计算完
16                 te = a[alen--] + up -'0';
17             else
18                 if(alen < 0 && blen >= 0)//如果a字符串已经计算完
19                     te = b[blen--] + up - '0';
20         if(te > 9)
21         {
22             up = te / 10;//得到进位值
23             te = te % 10;//得到余数
24         }
25         else
26             up = 0;
27         ans.push_back(te + '0');//将结果放进结果字符串
28     }
29     if(up)
30         ans.push_back(up + '0');//如果出现两个字符串一样长,而还有进位值
31 }
32 
33 int main()
34 {
35     string a,b;
36     int t,ca = 0,i;
37     cin >> t;
38     for(ca = 1;ca <= t;ca++)
39     {
40         cin >> a >> b;
41         bintadd(a,b);
42         if(ca != 1)
43             cout << endl;
44         cout << "Case" << " " << ca << ":" << endl;
45         cout << a << " + " << b << " = ";
46         for(i = ans.length() - 1;i >= 0;i--)//反向输出结果字符串
47             cout << ans[i];
48         cout << endl;
49         ans.erase();
50     }
51 }

代码分析:

上面的代码是我根据网上代码改正后的,我自己写的代码虽然答案正确,但没有上面的代码那么简洁,所以就用了网上的代码来分析,不过网上的这代码有错误,但竟然AC了。。。我改正后,也AC了。。

大数加法,主要就在于将数字存储为字符串,然后根据小学学的满十进一的原则,得出答案,最后反向输出。。。

参考地址:http://www.haogongju.net/art/1227474

转载于:https://www.cnblogs.com/linxiaotao/p/3413384.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值