Solution of 424 - Integer Inquiry

Problem Description
source: https://uva.onlinejudge.org/external/4/424.html

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

Solution:
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <deque>
#include <fstream>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
#include<stdio.h>
#include<stdlib.h>

using namespace std;
void Reverse();
void Reversec();
char a[105],c[150],b[105];
int i,j,k,len,len1,len2,carry,sum,n,val;
int main()
{
    memset(c,'\0',105);
    while(scanf("%s",b)==1)
    {
        if(strcmp(b,"0")==0)
        {
            memset(a,'\0',101);
            len=strlen(c);
            Reversec();
            printf("%s\n",a);
            memset(c,'\0',150);

        }
        carry=0;
        len1=strlen(b);
        Reverse();
        len2=strlen(c);
        if(len1>len2)
                n=len1;
            else
                n=len2;
        for(i=0;i<n;i++)
        {
            if(i>=len1)
                a[i]='0';
            if(i>=len2)
                c[i]='0';
            val=(c[i]-48)+(a[i]-48)+carry;
            sum=val%10;
            carry=val/10;
            c[i]=(sum+48);
        }
        if(carry>0)
            c[i]=(carry+48);
        memset(a,'\0',101);
        memset(b,'\0',101);
    }

    return 0;
}
void Reverse()
{
    k=0;
    for(j=len1-1;j>=0;j--)
    {
        a[k]=b[j];
        k+=1;
    }
}
void Reversec()
{
    k=0;
    for(j=len-1;j>=0;j--)
    {
        a[k]=c[j];
        k+=1;
    }
}

image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience