您的位置:首页 > 编程语言 > C语言/C++

POJ1503大数相加

2012-11-24 13:10 337 查看
Input
The input will consist of at most 100 lines of text, each of which contains a single VeryLongInteger. Each VeryLongInteger will be 100 or fewer characters in length, and will only contain digits (no
VeryLongInteger will be negative).

The final input line will contain a single zero on a line by itself.

Output
Your program should output the sum of the VeryLongIntegers given in the input.

Sample Input
123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0

Sample Output
370370367037037036703703703670

题目大意是:把各个整数加和,直到0结束
花了不少功夫才AC。主要原因是:输入的字符串有可能有前导零,这点最开始没有考虑进去

 
#include <iostream>
#include <string>
using namespace std;

void add(int a[],int & lena,int b[],int & lenb)//把加和的结果保存到a中,并记住lena;
{
int res[10001];
memset(res,0,sizeof(res));
int i;
int len=(lena>=lenb)?(lena+1):(lenb+1);
int ia=0,ib=0;
for (i=1;i<len;i++)//add;
{
if (i+lena>=len)
{
res[i]+=a[ia];
ia++;
}
if (i+lenb>=len)
{
res[i]+=b[ib];
ib++;
}
}
for (i=len-1;i>=0;i--)//process the carry;
{
if (res[i]>9)
{
res[i-1]+=res[i]/10;
res[i]=res[i]%10;
}
}
i=0;
while(res[i]==0)//skip the precursor zero;
{
i++;
}
lena=len-i;
for (int j=0;i<len;i++,j++)//store the result;
{
a[j]=res[i];
}
}
int main()
{

int numa[10001];
int numb[10001];
char s[101];
int lena=0,lenb=0;
cin>>s;
if (s[0]==0)
{
cout<<"0"<<endl;
return 0;
}
int i=0;
while(s[i]!=
8c4d
0)
{
lena++;
numa[i]=s[i]-'0';
i++;
}
memset(s,0,sizeof(s));
cin>>s;
while(strcmp(s,"0")!=0)//the mark of the end is "0";
{
i=0;
lenb=0;
while(s[i]!=0)
{
lenb++;
numb[i]=s[i]-'0';
i++;
}
add(numa,lena,numb,lenb);
memset(s,0,sizeof(s));
cin>>s;
}
for (i=0;i<lena;i++)
{
cout<<numa[i];
}
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ oj 高精度