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
题解:
会了之后就是模板一样的东西。
大数相加思路:将两个数输入到字符数组里面先存着。就像我们平时算加法那样,要从后面的数开始加一样 ,大数相加也要从后向前加,所以我们要先把大数倒序,同时因为存的是字符型数据,所以倒序的时候顺便让字符-'0',转化为10进制。之后把倒序的两个数组进行相加,逢10进1。注意最后输出的时候,再把顺序给倒过来,倒序输出。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int maxn=1010;
char a[maxn],b[maxn];//存两个大数
int c[maxn],d[maxn],e[maxn];//c、d数组存的分别是两个数组倒序后的十进制数,e数组存答案,e数组最后要倒序输出
int main()
{
// freopen("input.txt","r",stdin); //提交时关闭
// std::ios::sync_with_stdio(false);
int T;
cin>>T;
int th=0;
int f=0;
while(T--)
{
if(f) cout<<endl;
f=1;
th++;
memset(d,0,sizeof(d));
memset(e,0,sizeof(e));
memset(c,0,sizeof(c));
scanf("%s%s",a,b);
int lena=strlen(a);
int lenb=strlen(b);
int oppa=lena-1;//作为倒序后的下标
int oppb=lenb-1;
for(int i=0;i<lena;i++)
{
c[oppa]=a[i]-'0';//字符转化为十进制位
oppa--;
}
for(int i=0;i<lenb;i++)
{
d[oppb]=b[i]-'0';
oppb--;
}
int l=max(lena,lenb);
for(int i=0;i<l;i++)
{
e[i]+=c[i]+d[i];
if(e[i]>=10)//等于十也要考虑
{
e[i+1]++;//逢十进一
e[i]=e[i]%10;
}
}
printf("Case %d:\n",th);
printf("%s + %s = ",a,b);
if(e[l]!=0) cout<<e[l];//考虑两个数相加,最后最大位向前进一位的情况
for(int i=l-1;i>=0;i--)
cout<<e[i];
cout<<endl;
}
return 0;
}