UVa Solution : 713 – Adding Reversed Number


The problem link is
 UVa:713-Adding Reversed Number

Solution:

#include<stdio.h>
#include<string.h>
void GetReverse(char *str)
{
    int j,lenth;
    char tmp;
    lenth = strlen(str);
    for(j=0;j<lenth/2;j++)
    {
        tmp = str[j];
        str[j] = str[lenth-j-1];
        str[lenth-j-1] = tmp;
    }
}
int main()
{
    char str1[200],str2[200];
    int test_case,i,j,k,lenth1,lenth2,lenth,carry,sum[200],tmp;
    scanf("%d",&test_case);
    for(i=0;i<test_case;i++)
    {
        tmp = 0;
        carry = 0;
        scanf("%s %s",&str1,&str2);
        lenth1 = strlen(str1);
        lenth2 = strlen(str2);
        /*assign trailing zero for different lenth of two string*/
        if(lenth1>lenth2)
        {
            lenth = lenth1;
            for(j=0;j<lenth-lenth2;j++)
                str2[lenth2+j] = '0';
            str2[lenth2+j] = '\0';
        }
        else
        {
            lenth = lenth2;
            for(j=0;j<lenth-lenth1;j++)
                str1[lenth1+j] = '0';
            str1[lenth1+j] = '\0';
        }
        GetReverse(str1);
        GetReverse(str2);
        /*summation and get output reverse*/
        for(j=0;j<lenth;j++)
        {    
            sum[j]=((str1[lenth-j-1]-'0')+(str2[lenth-j-1]-'0') + carry)%10;
            carry = ((str1[lenth-j-1]-'0')+(str2[lenth-j-1]-'0')+ carry)/10;
            if(j+1 == lenth && carry == 1)
            {
                j++;
                sum[j] = carry;
            }
        }
        sum[j] = -1;
        /*print without leading zero*/
        for(k=0;k<j;k++)
        {
            if(sum[k]== 0 && tmp== 0)
                continue;
            else
            {
                tmp = 1;
                printf("%d",sum[k]);
            }

        }
        printf("\n");
    }    
    return 0;
}

Run time: 0.012
User Name on UVA: refatsardar

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: