大数相加

大数相加:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002

1.程序中大数的输入采用的是字符串的形式(C语言中的char数组或者C++中的string字符串)

2.存放相加后结果的数组定义成int类型会比较容易书写

3.后尾对齐,满十进一的原则

4.相加的两个大数可能长度不同,因此在相加以后需要判断是否相加完

5.9+2相加之后位数发生变化,所以最后要注意判断相加之后的首位是否为0

代码:

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char a[1100],b[1100];
int t,lena,lenb,k,y,i,j;
cin>>t;
for (int m=1;m<=t;m++)
{
int c[1200]={0};
cout << "Case " << m << ":" << endl;
cin>>a>>b;
k=0;
lena=strlen(a);
lenb=strlen(b);
cout << a << " + " << b << " = " ;
for (i=lena-1,j=lenb-1;i>=0&&j>=0;i--,j--)
{
y=a[i]-'0'+b[j]-'0';
if (y+c[k]>=10)
{
c[k+1]++;
c[k]+=y-10;
}
else
c[k]=c[k]+y;
k++;
}
if (k<lena)
{
for (int x=i;x>=0;x--)
{
c[k]+=a[x]-'0';
k++;
}
}
else if (k<lenb)
{
for (int x=j;x>=0;x--)
{
c[k]+=b[x]-'0'; k++;
}
}
else if (c[k]!=0)
k++;
for (int z=k-1;z>=0;z--)
cout << c[z] ; cout << endl;
if (m!=t) cout << endl ;
} return 0;
}
原文地址:https://www.cnblogs.com/lisijie/p/7197488.html