A + B Problem II
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 409341 Accepted Submission(s): 79315
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
21 2112233445566778899 998877665544332211
Sample Output
Case 1:1 + 2 = 3Case 2:112233445566778899 + 998877665544332211 = 1111111111111111110
Author
Ignatius.L
解题思路:这是道大数加法问题,由于输入的数字可能会比较大,所以我们把输入当做字符串来存;然后分别倒叙存入数组中,让2个数组进行计算,从第一项开始,像小学加法算术一样,大于10就前一位进1,存入一个新数组;最后把新数组倒序输出。
例:1234+567
| 0 | 1 | 2 | 3 |
S1 | 1 | 2 | 3 | 4 |
S2 | 5 | 6 | 7 |
|
| 0 | 1 | 2 | 3 |
S3 | 4 | 3 | 2 | 1 |
S4 | 7 | 6 | 5 |
|
s | 1 | 0 | 8 | 1 |
然后把s倒序输出
1234 + 567 = 1801
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n;
cin>>n;
for(int k=1;k<=n;k++)
{
char s1[1005],s2[1005];
int s3[1005],s4[1005],s[1100]={0};
scanf("%s%s",s1,s2);
int l1=strlen(s1);
int l2=strlen(s2);
for(int i=l1-1,j=0;i>=0;i--,j++)//倒序存入数组,记得-1,因为字符串是从0开始存入的,最后一位是s3[l1-1]
s3[j]=s1[i]-'0';
for(int i=l2-1,j=0;i>=0;i--,j++)
s4[j]=s2[i]-'0';
for(int i=0;i<min(l1,l2);i++)//先将min(l1,l2)存入数组
{
s[i]=s3[i]+s4[i]+s[i];//加s[i]是因为后一位可能会进1
if(s[i]>=10)
{
s[i+1]=1;//如果和大于10,就要前一位进1
s[i]=s[i]-10;
}
}
for(int i=min(l1,l2);i<max(l1,l2);i++)//把剩下的存入数组
{
if(l1>l2)//判断是哪个剩下了
s[i]=s3[i]+s[i];
if(l1<l2)
s[i]=s4[i]+s[i];
}
cout<<"Case "<<k<<':'<<endl;//注意输出格式
cout<<s1<<" "<<'+'<<" "<<s2<<" "<<'='<<" ";
for(int i=max(l1,l2)-1;i>=0;i--)//倒序输出
cout<<s[i];
if(k!=n)//注意格式,除了最后一组测试是一个换行,其他都是两个换行
cout<<endl<<endl;
else
cout<<endl;
}
}