Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #include<string>
  3. using namespace std;
  4.  
  5. string add(string a, string b){
  6.     string res="";
  7.     while(a.length() < b.length()) a="0"+a;
  8.     while(b.length() < a.length()) b="0"+b;
  9.     int carry=0;
  10.     for(int i=a.length()-1;i>=0;i--){
  11.         int tmp=a[i]-48 + b[i]-48 + carry;
  12.         carry=tmp/10;
  13.         tmp=tmp%10;
  14.         res=(char)(tmp+48)+res;
  15.     }
  16.     if(carry>0) res="1"+res;
  17.     return res;
  18. }
  19.  
  20. string sub(string a, string b){
  21.     string res="";
  22.     while(a.length() < b.length()) a="0"+a;
  23.     while(b.length() < a.length()) b="0"+b;
  24.     bool neg=false;
  25.     if(a<b){
  26.         swap(a,b);
  27.         neg=true;
  28.     }
  29.     int borrow=0;
  30.     for(int i=a.length()-1; i>=0;i--){
  31.         int tmp=a[i]-b[i]-borrow;
  32.         if(tmp<0){
  33.             tmp+=10;
  34.             borrow=1;
  35.         }
  36.         else borrow=0;
  37.         res=(char)(tmp%10 + 48) + res;
  38.     }
  39.     while(res.length()>1 && res[0]=='0') res.erase(0,1);
  40.     if(neg) res="-"+res;
  41.     return res;
  42. }
  43.  
  44. string mul(string a, string b){
  45.     string res="";
  46.     int n=a.length();
  47.     int m=b.length();
  48.     int len=n+m-1;
  49.     int carry=0;
  50.     for(int i=len;i>=0;i--){
  51.         int tmp=0;
  52.         for(int j=n-1;j>=0;j--)
  53.             if(i-j<=m && i-j>=1){
  54.                 int a1=a[j]-48;
  55.                 int b1=b[i-j-1]-48;
  56.                 tmp+=a1*b1;
  57.             }
  58.             tmp+=carry;
  59.             carry=tmp/10;
  60.             res=(char)(tmp%10 + 48)+res;
  61.     }
  62.     while(res.length()>1 && res[0]=='0') res.erase(0,1);
  63.     return res;
  64. }
  65. int main(){
  66.    
  67.     string a, b;
  68.     cin>>a>>b;
  69.     cout<<add(a,b)<<endl;
  70.     cout<<sub(a,b)<<endl;
  71.     cout<<mul(a,b);
  72.    
  73.     return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement