Saturday, March 18, 2017

Solution of Dev Skill DCP-1: Big Sum

See the problem  Big Sum
/*  Bismillahir Rahmanir Rahim
    Problem-Logical.
The following code is bulky in size but logic is simple. 
 456
 789
-----
 1461 (its the answer)[add start from left to right]
*/
#include<bits/stdc++.h>
using namespace std;

int main(){
    string s;
    while(cin>>s){
        char s1[109], s2[109];
        int i, temp, c=0, fl=0, sz1, sz2, y=0, x=0;
        for(i=0; i<s.size(); i++){
            if(s[i]==',') fl=1;
            else if(!fl) s1[x++]=s[i]; // until getting ','
            else s2[y++]=s[i]; // after getting ','
        }
        fl=0;
        if(x>=y){   // if(first string >= second string)
            for(i=0; i<y; i++){
                temp=(int)(s1[i]-'0')+(int)(s2[i]-'0')+c;
                if(temp==10){
                    if(fl)cout<<0; c=1;
                }
                else if(temp>10){
                    cout<<temp%10; c=1; fl=1;
                }
                else{
                    cout<<temp; c=0; fl=1;
                }
            }
            for(i=y; i<x; i++){ // after ending of second string
                temp=(int)(s1[i]-'0')+c;
                if(temp==10){
                    if(fl)cout<<0; c=1;
                }
                else if(temp>10){
                    cout<<temp%10; c=1; fl=1;
                }
                else{
                    cout<<temp; c=0; fl=1;
                }
            }
        }
        else{  // same as before, just replace y with x & x with y
            for(i=0; i<x; i++){
                int temp=(int)(s1[i]-'0')+(int)(s2[i]-'0')+c;
                if(temp==10){
                    if(fl)cout<<0; c=1;
                }
                else if(temp>10){
                    cout<<temp%10; c=1; fl=1;
                }
                else{
                    cout<<temp; c=0; fl=1;
                }
            }
            for(i=x; i<y; i++){
                temp=(int)(s2[i]-'0')+c;
                if(temp==10){
                    if(fl)cout<<0; c=1;
                }
                else if(temp>10){
                    cout<<temp%10; c=1; fl=1;
                }
                else{
                    cout<<temp; c=0; fl=1;
                }
            }
        }
        if(c) cout<<c%10;
        cout<<endl;
    }
    return 0;
}

No comments:

Post a Comment