Mephistopheles_

Сalculator

Sep 6th, 2021 (edited)
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. void solution(){
  2.     stack<char> stk;
  3.     string s;
  4.     cin>>s;
  5.     string up="*/",ni="-+";
  6.     vector<string>res;
  7.     forx(i,0,isz(s)){
  8.         string u="";
  9.         if (isdigit(s[i])){
  10.             while (isdigit(s[i])){
  11.                 u+=s[i];
  12.                 ++i;
  13.             }
  14.             --i;
  15.             res.push_back(u);
  16.         }
  17.         else if(s[i]=='(')
  18.             stk.push(s[i]);
  19.         else if(s[i]==')'){
  20.             while(stk.top()!='(' && isz(stk)>0){
  21.                 u="";
  22.                 u+=stk.top();
  23.                 res.push_back(u);
  24.                 stk.pop();
  25.             }
  26.             if(isz(stk)>0)
  27.                 stk.pop();
  28.         }
  29.         else{
  30.             if(isz(stk)==0 || up.find(s[i])!=string::npos && ni.find(stk.top())!=string::npos)
  31.                 stk.push(s[i]);
  32.             else{
  33.                 while(isz(stk)>0 && (up.find(stk.top())!=string::npos && ni.find(s[i])!=string::npos || up.find(stk.top())!=string::npos && up.find(s[i])!=string::npos  || \
  34.                 ni.find(stk.top())!=string::npos && ni.find(s[i])!=string::npos)){
  35.                     u="";
  36.                     u+=stk.top();
  37.                     res.push_back(u);
  38.                     stk.pop();
  39.                 }
  40.                 stk.push(s[i]);
  41.             }
  42.         }
  43.     }
  44.     string u;
  45.     while(isz(stk)>0){
  46.         u="";
  47.         u+=stk.top();
  48.         res.push_back(u);
  49.         stk.pop();
  50.     }
  51.     stack<int>stk2;
  52.     for(auto& a:res){
  53.         if(up.find(a)==string::npos && ni.find(a)==string::npos)
  54.             stk2.push(stoi(a));
  55.         else{
  56.             int x=stk2.top();
  57.             stk2.pop();
  58.             int y=stk2.top();
  59.             stk2.pop();
  60.             if(a=="+")
  61.                 stk2.push(x+y);
  62.             if(a=="-")
  63.                 stk2.push(x-y);
  64.             if(a=="*")
  65.                 stk2.push(x*y);
  66.             if(a=="/")
  67.                 stk2.push(x/y);
  68.         }
  69.     }
  70.     cout<<stk2.top();
  71.  
  72. }
Add Comment
Please, Sign In to add comment