ps:正好有朋友问这题,就写了个超多注释的超详细版代码。每步都有解释。希望也能帮到其他人。
问题:
A + B Problem IITime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 434632 Accepted Submission(s): 84594 Problem DescriptionI 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 Input2 1 2 112233445566778899 998877665544332211
Sample Output
Case 1: 1 + 2 = 3
Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
|
代码:
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int i,j,y,n,k,h,p,lena,lenb;//先定义一批变量,用于以后存数
int a[1010]={0},b[1010]={0},sum[1010]={0},f[1010]={0};//存大数位,加和,全部遍历为0 ,为了让之后的判断更方便
int main()
{
string a1,b1;//定义两个字符串先把数输入进来
cin>>n;//输入n组数据
for(y=1;y<=n;y++)
{
cin>>a1>>b1;//输入大数
lena=a1.length();//看两个大数的数位
lenb=b1.length();
//a1,b1字符串中的字符a转化为数
for(i=lena-1;i>=0;i--)
a[lena-1-i]=a1[i]-'0';
for(i=lenb-1;i>=0;i--)
b[lenb-1-i]=b1[i]-'0';
//用k来判断a+b会不会超过10 进位
k=0;
//进行逐位a+b,用f【】存放
for(i=0;i<lenb||i<lena;i++)
{
h=a[i]+b[i]+k;
f[i]=h%10;
k=h/10;
}
//进行一个判断看是否最后一味相加也进位
if(k!=0)
f[i++]=k;
cout<<"Case "<<y<<":"<<endl<< a1 <<" + "<< b1 <<" = ";
for(j=i-1;j>=0;j--)
{
cout<<f[j];
}
cout<<endl<<endl;
}
return 0;
}