Big sum(nsu question)



#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main()
{
    int c,d,e,l,x,y;
    string a,b;
    char f[1000],g[1000];
    cin>>a>>b;
    c=a.size();
    d=b.size();
    if(c>d)
    {
        e=c-d;
        for(int i=0; i<e; i++)
        {
            f[i]='0';
        }
        l=0;
        for(int i=e; i<e+d; i++)
        {
            f[i]=b[l];
            l++;
        }
        l=0;
        int temp=0;
        int temp1=0;
        for(int i=c-1; i>=0; i--)
        {
            x=a[i]-'0';
            y=f[i]-'0';
            y=y+temp1;
            if(x+y<=9)
            {
                g[l]=(x+y)+'0';
                temp1=0;
            }
            else
            {
                //int temp,temp1;
                temp=(x+y)%10;
                temp1=(x+y)/10;
                //cout<<temp<<" "<<temp1<<endl;
                g[l]=temp+'0';
                //cout<<g[l]<<endl;
                y=f[i+1]-'0';
                //y=y+temp1;
                f[i+1]=y+'0';
            }
            l++;
        }
        //l++;
        //cout<<temp1<<endl;
        if(temp1!=0)
        {
            char f1=temp1+'0';
            //cout<<f1<<endl;
            g[l]=f1;
            l++;
        }
    }
    else if(c<=d)
    {
        e=d-c;
        for(int i=0; i<e; i++)
        {
            f[i]='0';
        }
        l=0;
        for(int i=e; i<e+c; i++)
        {
            f[i]=a[l];
            l++;
        }
        l=0;
        int temp=0;
        int temp1=0;
        for(int i=d-1; i>=0; i--)
        {
            x=b[i]-'0';
            y=f[i]-'0';
            y=y+temp1;
            if(x+y<=9)
            {
                g[l]=(x+y)+'0';
                temp1=0;
            }
            else
            {
                //int temp,temp1;
                temp=(x+y)%10;
                temp1=(x+y)/10;
                //cout<<temp<<" "<<temp1<<endl;
                g[l]=temp+'0';
                //cout<<g[l]<<endl;
                y=f[i+1]-'0';
                //y=y+temp1;
                f[i+1]=y+'0';
            }
            l++;
        }
        //l++;
        //cout<<temp1<<endl;
        if(temp1!=0)
        {
            char f1=temp1+'0';
            //cout<<f1<<endl;
            g[l]=f1;
            l++;
        }
    }
    //cout<<l<<endl;
    for(int i=l-1; i>=0; i--)
    {
        cout<<g[i];
    }
}

Comments

Popular posts from this blog

C++ STL practice problem link

Binary Index Tree(BIT)

Combinatorics