博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ZOJ_1292 大整数相加

Posted on 2010-08-03 21:00  还好  阅读(1032)  评论(0编辑  收藏  举报
Integer Inquiry

Time Limit: 1 Second      Memory Limit: 32768 KB

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.


This problem contains multiple test cases!

The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.

The output format consists of N output blocks. There is a blank line between output blocks.


Sample Input

1

123456789012345678901234567890
123456789012345678901234567890
123456789012345678901234567890
0

 原题地址: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=292

转化一下题目,意思就是求解大整数的之和!这里涉及到将一个只包含数字的字符串转化成对应的整数数组的算法!下面是我写的C++代码!

Run Time: 0MS Run Memory:184KB

 

代码
#include<iostream>
#include
<string>

using namespace std;

void Convert(string s, int* a)//将对应的字符串转化成对应的整形数组
{
    
int len=s.length();
    
for(int i=len-1,j=0;i>=0;i--,j++)
    {
        a[j]
=s[i]-'0';
    }
}

void Add(int*a, int len1,int* b, int len2)//两个大整数求和,和保存在数组a中
{
    
int i,sum;
    
int min=len1<=len2?len1:len2;
    
for(i=0;i<min;i++)
    {
        sum
=a[i]+b[i];
        
if(sum>=10)
        {
            a[i]
=sum-10;
            a[i
+1]++;
        }
        
else
        {
            a[i]
=sum;
        }
    }
}

int main(void)
{
    
int n;
    cin
>>n;
    
while(n>0)
    {
        
int a[201];        
        
int b[100];
        
int i;
        
for(i=0;i<201;i++)a[i]=0;
        
string s;
        
while(cin>>s&&s.compare("0")!=0)
        {
            Convert(s,b);
            Add(a,
201,b,s.length());
        }
        i
=200;
        
while(a[i]==0)i--;
        
while(i>=0){cout<<a[i];i--;}
        cout
<<endl;

        n
--;
        
if(n>0)cout<<endl;
    }
    
return 0;
}