题目描述:
Description
One of the first users of BIT's new supercomputer was Chip Diller. He extended his exploration of powers of 3 to go from 0 to 333 and he explored taking various sums of those numbers.
``This supercomputer is great,'' remarked Chip. ``I only wish Timothy were here to see these results.'' (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
``This supercomputer is great,'' remarked Chip. ``I only wish Timothy were here to see these results.'' (Chip moved to a new apartment, once one became available on the third floor of the Lemon Sky apartments on Third Street.)
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.
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
思路:大数加法!!
代码:
#include<iostream>
#include<string>
using namespace std;
int a[105],b[105];
char str[105];
int main()
{
int i,j,len1=0,len2=0,temp1,temp2;
memset(a,0,sizeof(a));
while(gets(str))
{
if(str[0]=='0'&&strlen(str)==1){break;}
len1=strlen(str);
memset(b,0,sizeof(b));
for(i=0;i<len1;i++) b[i]=str[i]-'0';
if(len2==0)
{
for(i=0;i<len1;i++) {a[i]=b[i];}
len2=len1;
}
else
{
if(len1>len2)
{
j=len2-1;
for(i=len1-1;i>=0;i--)
{
if(j>=0){a[i]=a[j--]+b[i];}
else a[i]=b[i];
}
len2=len1;
}
else
{
j=len1-1;
for(i=len2-1;i>=0;i--)
{
if(j>=0){a[i]=a[i]+b[j--];}
else break;
}
}
}
}
temp1=0; temp2=0;
for(i=len2-1;i>0;i--)
{
if(a[i]>=10) {a[i-1]+=a[i]/10;a[i]=a[i]%10;}
}
if(a[0]>=10){temp1=a[i]/100;temp2=(a[0]%100)/10;a[0]=a[0]%10;}
if(temp1>0){printf("%d",temp1);}
if(temp1>0&&temp2>=0){printf("%d",temp2);}
for(i=0;i<len2;i++) {printf("%d",a[i]);}
printf(" \n");
// system("pause");
return 0;
}
本文介绍了一种使用C++实现的大数加法算法,通过数组存储多位数字,并提供了示例代码来解决输入多个大整数并求和的问题。

1186

被折叠的 条评论
为什么被折叠?



