UVA 713 - Adding Reversed Numbers Solution

UVA 713 - Adding Reversed Numbers Solution 



'0'+'0'=96    (48+48) 48 is the ASCII value of zero.
Sum of two char  is 96 is means 0.
Sum value 97 means 1..... Sum value 105 means 9.
Sum value 106 means 10. So, result is 0 and carry is 1. which add to next chars sum.

CODE:


#include<iostream>
#include<map>
#include<algorithm>
#include<string>

using namespace std;


int trailZero(string str)
{
     int index=0;
     while(str[index]=='0')
     {
        index++;
     }
     return index;
}
int main()
{
    map<char,char> charToInt;
    string s1,s2,s3;
    char ch;
    int i,len1,len2,max_len,carry,test;
    for(i=0;i<10;i++)
        charToInt[i+96]=i+48;
    cin>>test;
    while(test--)
    {
        cin>>s1>>s2;
        len1=s1.length();
        len2=s2.length();
        max_len=max(len1,len2);
        reverse(s1.begin(),s1.end());
        reverse(s2.begin(),s2.end());
        if(len1>len2)
            s2.insert(0,len1-len2,'0');
        else if(len1<len2)
            s1.insert(0,len2-len1,'0');
        carry=0;
        s3="";
        for(i=max_len-1;i>=0;i--)
        {
            ch=s1[i]+s2[i];
            if(carry)
                ch++;
            if(ch>105)
            {
                ch=ch-10;
                carry=1;
            }
            else
                carry=0;
            s3.insert(0,1,charToInt[ch]);
        }
        if(carry)
            s3.insert(0,1,'1');
        reverse(s3.begin(),s3.end());
        i=trailZero(s3);
        len1=s3.length()-i;
        s3=s3.substr(i,len1);
        cout<<s3<<endl;
    }
    return 0;
}

Comments

Popular posts from this blog

uva 481 - What Goes Up Solution

uva - 787 - Maximum Sub-sequence Product Solution

UVA 10617 Solution - Again Palindrome