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.)
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
问题描述
将多个数加起来后输出。
问题分析
高精度计算。注意进位,尤其是最高位处,容易忽略掉。还有字符和数字的转换也是需要注意的。
c++程序如下
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
string num[2];
num[0]="0";
while(cin>>num[1])
{
if(num[1]=="0")break;
if(num[0]=="0")
{
num[0]=num[1];
continue;
}
int am,bm,t,i,j,mid,len[2];
char str[105];
memset(str,'\0',sizeof(str));
len[0]=num[0].size(),len[1]=num[1].size();
if(len[0]<len[1])
{
swap(len[0],len[1]);
swap(num[0],num[1]);
}
for(i=len[0]-1,j=len[1]-1,mid=t=0;i>=0;i--)
{
if(j>=0)
{
bm=num[1][j]-'0';
mid+=bm;
j--;
}
am=num[0][i]-'0';
mid+=am+t;
str[i]=mid%10+'0';
t=mid/10;
mid=0;
}
num[0]="";
if(t>0)num[0]+=t+'0';
num[0]+=str;
}
cout<<num[0]<<endl;
return 0;
}