Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <math.h>
- #include <iostream>
- #include <string>
- using namespace std;
- string add (string x , string y)
- {
- int xs=x.size() ,ys=y.size() ;
- if ( xs < ys)
- {
- for (int b=0 ; b <(ys-xs) ;b++ )
- x.insert(x.begin(), '0');
- }
- else if ( xs > ys)
- {
- for (int b=0 ; b <(xs-ys) ;b++ )
- y.insert(y.begin(), '0');
- }
- string h; int carry=0 ,s=0;
- for(int i=(x.size()-1) ;i>=0 ;i--)
- {
- int f=x[i]-48 , j=y[i]-48 ;
- if (xs>=ys)
- s=f-j-carry;
- if (ys>xs)
- s=j-f-carry;
- //cout<<s<<"#\n";
- if (s==0 && i==0)
- break;
- if (s<0)
- {
- if (i!=0)
- {
- h.insert(h.begin() ,((s+10)+48));
- carry=1;
- }
- if (i==0)
- {
- s=-s;
- h.insert(h.begin() ,s+48);
- h.insert(h.begin() ,'-');
- }
- }
- else
- {
- h.insert(h.begin() ,(s+48));
- carry=0;
- }
- }
- while(h.size()-1&&h[0]=='0')
- h.erase(0,1);
- if (ys>xs)
- h.insert(h.begin() ,'-');
- return h;
- }
- int main ()
- {
- freopen("myDearInput.in", "r", stdin);
- int n;
- cin>>n;
- for (int i=0 ; i<n ; i++)
- {
- string x ,y;
- cin >> x;
- cin >> y ;
- y= add(x,y);
- cout<<y<<endl;
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment