Guest User

Untitled

a guest
Jun 19th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <math.h>
  2. #include <iostream>
  3. #include <string>
  4. using namespace std;
  5. string add (string x , string y)
  6. {
  7.     int xs=x.size() ,ys=y.size() ;
  8.  
  9.     if ( xs < ys)
  10.     {
  11.         for (int b=0 ; b <(ys-xs) ;b++ )
  12.             x.insert(x.begin(), '0');
  13.     }
  14.  
  15.  
  16.     else if ( xs > ys)
  17.     {
  18.         for (int b=0 ; b <(xs-ys) ;b++ )
  19.             y.insert(y.begin(), '0');
  20.     }
  21.  
  22.     string  h; int carry=0 ,s=0;
  23.  
  24.     for(int i=(x.size()-1) ;i>=0 ;i--)
  25.     {
  26.  
  27.         int f=x[i]-48 , j=y[i]-48 ;
  28.         if (xs>=ys)
  29.         s=f-j-carry;
  30.         if (ys>xs)
  31.             s=j-f-carry;
  32.         //cout<<s<<"#\n";
  33.         if (s==0 && i==0)
  34.             break;
  35.         if (s<0)
  36.         {
  37.             if (i!=0)
  38.             {
  39.                 h.insert(h.begin() ,((s+10)+48));
  40.                 carry=1;
  41.             }
  42.             if (i==0)
  43.             {
  44.                 s=-s;
  45.                 h.insert(h.begin() ,s+48);
  46.                 h.insert(h.begin() ,'-');
  47.             }
  48.  
  49.         }
  50.         else
  51.         {
  52.             h.insert(h.begin() ,(s+48));
  53.             carry=0;
  54.         }
  55.     }
  56.     while(h.size()-1&&h[0]=='0')
  57.         h.erase(0,1);
  58.     if (ys>xs)
  59.         h.insert(h.begin() ,'-');
  60.     return h;
  61. }
  62. int main ()
  63. {
  64.     freopen("myDearInput.in", "r", stdin);
  65.     int n;
  66.     cin>>n;
  67.     for (int i=0 ; i<n ; i++)
  68.     {
  69.         string x ,y;
  70.         cin >> x;
  71.         cin >> y ;
  72.         y= add(x,y);
  73.         cout<<y<<endl;
  74.     }
  75.     return 0;
  76. }
Add Comment
Please, Sign In to add comment