您的位置:首页 > 其它

大数加法

2015-03-27 20:21 218 查看
[align=left]Problem Description[/align]
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.

 

[align=left]Input[/align]
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.

 

[align=left]Output[/align]
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.

 

[align=left]Sample Input[/align]

2
1 2
112233445566778899 998877665544332211

 

[align=left]Sample Output[/align]

Case 1:
1 + 2 = 3

Case 2:
112233445566778899 + 998877665544332211 = 1111111111111111110

题意非常简单。就是求大数的加法。这时候用正常的加法肯定是不行的,所以我们引入了大数加法这个概念。
通过string类或者字符数组来对这些数字进行储存,然后用模拟的思想将他模拟出来
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;
string a,b;
string jia(string a,string b)
{
while(a.size()<b.size())
{
a='0'+a;
}
while(a.size()>b.size())
{
b='0'+b;
}
a='0'+a;
b='0'+b;
for(int i=a.size()-1; i>=0; i--)
{
a[i]=a[i]+b[i]-'0';
if(a[i]>'9')
{
a[i]-=10;
a[i-1]++;
}
}
while(a.size()>1&&a[0]=='0')
a.erase(0,1);
return a;
}
int main()
{
int t,T=0;
cin >> t;
while(t--)
{
T++;
cin >> a >> b;
string c=jia(a,b);
printf("Case %d:\n",T);
cout << a << " + " << b << " = " << c << endl;
if(t!=0)
cout << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: