Advertisement
imashutosh51

Evaluate reverse polish notation

Oct 16th, 2022
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. /*
  2. Logic:
  3. push numbers into stack and whenever operators comes pop top two items
  4. and operate on them and push the result.
  5. */
  6. long long int _stoi(string s){
  7.     bool sign=false;
  8.     long long int ans=0;
  9.     int i=0;
  10.     if(s[0]=='-'){sign=true; i++;}
  11.     while(i<s.size()){
  12.         ans=ans*10+(s[i]-'0');
  13.         i++;
  14.     }
  15.     if(sign) return -ans;
  16.     return ans;
  17. }
  18. class Solution {
  19. public:
  20.     int evalRPN(vector<string>& arr) {
  21.         stack<long long int> st;
  22.         for(auto itr:arr){
  23.             if(itr=="+" || itr=="-" || itr=="*" || itr=="/"){
  24.                 long long int b=st.top(); st.pop();
  25.                 long long int a=st.top();st.pop();
  26.                 if(itr=="+") st.push(a+b);
  27.                 else if(itr=="-") st.push(a-b);
  28.                 else if(itr=="*") st.push(a*b);
  29.                 else st.push(a/b);
  30.             }
  31.             else st.push(_stoi(itr));
  32.         }
  33.         return st.top();
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement