A + B Problem II
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 108 Accepted Submission(s) : 21
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
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
Author
Ignatius.L
此题的数据若为64位以内,那做起来就so easy,但它的数据远超过了64位,只好按数组处理了,另外还要注意输出格式。
算法:首先思考一下中学时计算多位数时的竖式算法,对应位相加,满十进一。此题就是用这种方法,把计算得来的每一位存入数组,大数相加便解决了。
输入包括多组数据,第一行输入处理的数据数n,接下来输入n行,每行输入两个数a和b.题目要求算出a+b,
输出格式为:
case空格x:
a空格+空格b空格=空格a+b
每组结果之间有一个空行最后一组没有
代码:
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char a[10000],b[10000];
int h,p,k,j=0,i=0,n,s,la,lb,j1,i1;
cin>>n;
for(s=1;s<=n;s++)
{
int s1[10001]={0},s2[10001]={0},s3[100000]={0};
cin>>a;//输入字符串a
la=strlen(a);//测量字符串的长度
//把字符串a转换成数组
for(i=la-1,i1=0;i>=0;i--,i1++)
{
s1[i1]=a[i]-48;
}
//字符串b同a处理
cin>>b;
lb=strlen(b);
for(j=lb-1,j1=0;j>=0;j1++,j--)
{
s2[j1]=b[j]-48;
}
p=((lb<la)? la:lb);//比较字符串a和b的长度把大数赋给p
h=0;
for(k=0;k<p;k++)
{
s3[k]=(s1[k] + s2[k] + h) % 10;
h= (s1[k] + s2[k] + h) / 10;
}
cout<<"Case"<<' '<<s<<":"<<endl;
cout<<a<<' '<<"+"<<' '<<b<<' '<<"="<<' ';
if(s3[k]!=0) cout<<'1';
for(j=k-1;j>=0;j--)
{
cout<<s3[j];
}
cout<<endl;
if(s<n)
cout<<endl;
}
return 0;
}