Advertisement
urmisaha

Postfix Evaluation

Oct 28th, 2019
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.81 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int T;
  5. string s;
  6. stack<int> st;
  7.  
  8. bool isoperator(char x){
  9.     if(x == '+' || x == '-' || x == '*' || x == '/')
  10.         return true;
  11.     return false;
  12. }
  13.  
  14. int operation(int a, int b, char op){
  15.     if(op == '+')
  16.         return a+b;
  17.     if(op == '-')
  18.         return a-b;
  19.     if(op == '*')
  20.         return a*b;
  21.     if(op == '/')
  22.         return a/b;
  23. }
  24.  
  25. int main()
  26. {
  27.     cin>>T;
  28.     while(T--){
  29.         cin>>s;
  30.         for(int i=0; i<s.length(); ++i){
  31.             if(isoperator(s[i])){
  32.                 int b = st.top();
  33.                 st.pop();
  34.                 int a = st.top();
  35.                 st.pop();
  36.                 st.push(operation(a, b, s[i]));
  37.             }
  38.             else
  39.                 st.push(s[i] - '0');
  40.         }
  41.         cout<<st.top()<<endl;
  42.         st.pop();
  43.     }
  44.     return 0;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement