Advertisement
VladSmirN

Решение префиксного выражения

Apr 24th, 2021
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.  
  8. string str = "* - 5 8 7"; // (5-8)*7
  9. stack<int>st1;
  10. stack<char>st2;
  11. for(int i=str.size()-1;i>=0;--i){
  12.     if(str[i] == '*')st2.push('*'); else
  13.     if(str[i] == '+')st2.push('+'); else
  14.     if(str[i] == '-')st2.push('-'); else
  15.     {        //если число
  16.         if(str[i] != ' ')
  17.         st1.push(str[i] - '0');
  18.     }
  19.  
  20.     if (st2.size()>0 && st1.size() >= 2){
  21.  
  22.         int a = st1.top(); st1.pop();
  23.         int b = st1.top(); st1.pop();
  24.         char c = st2.top(); st2.pop();
  25.  
  26.         if(c == '+') st1.push(a+b);
  27.         if(c == '-') st1.push(a-b);
  28.         if(c == '*') st1.push(a*b);
  29.     }
  30.  
  31.  
  32. }
  33. int ans = st1.top(); st1.pop();
  34. cout<<ans;
  35.     return 0;
  36. }
  37.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement