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

代码如下:

 #include<iostream>
#include<string>
using namespace std;
string ans;
void bintadd(string a,string b)
{
int alen = a.length() - ,blen = b.length() - ;//alen,blen分别存放a,b字符串的最大下标
int up = ,i = ,j,te;//up存放进位值,te存放余数 while(alen >= || blen >= )
{
if(alen >= && blen >= )//两个字符串都没有计算完
te = a[alen--] + b[blen--] + up -'' - '';//倒着计算字符串里的数,记得要加上进位值up
else
if(alen >= && blen < )//如果b字符串已经计算完
te = a[alen--] + up -'';
else
if(alen < && blen >= )//如果a字符串已经计算完
te = b[blen--] + up - '';
if(te > )
{
up = te / ;//得到进位值
te = te % ;//得到余数
}
else
up = ;
ans.push_back(te + '');//将结果放进结果字符串
}
if(up)
ans.push_back(up + '');//如果出现两个字符串一样长,而还有进位值
} int main()
{
string a,b;
int t,ca = ,i;
cin >> t;
for(ca = ;ca <= t;ca++)
{
cin >> a >> b;
bintadd(a,b);
if(ca != )
cout << endl;
cout << "Case" << " " << ca << ":" << endl;
cout << a << " + " << b << " = ";
for(i = ans.length() - ;i >= ;i--)//反向输出结果字符串
cout << ans[i];
cout << endl;
ans.erase();
}
}

代码分析:

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

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

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

上一篇:【大数加法】POJ-1503、NYOJ-103


下一篇:c#大数加法