Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
723 B
0
Indexable
class Solution {
public:
    int evalRPN(vector<string>& arr) {
        stack<int>s; int n=arr.size();
        for(int i=0;i<n;i++){
            if(arr[i]!="*" && arr[i]!="+" && arr[i]!="-" && arr[i]!="/") {
                s.push(stoi(arr[i]));
            }else{
                if(s.empty()) return -1;
                int n1=s.top(); s.pop();
                 if(s.empty()) return -1;
                int n2=s.top(); s.pop();
                if(arr[i]=="+") s.push(n1+n2);
                else if(arr[i]=="*") s.push(n1*n2);
                else if(arr[i]=="-") s.push(n2-n1);
                else if(arr[i]=="/") s.push(n2/n1);
            }
        }
        if(!s.empty()) return s.top();
        return -1;
    }
};
Leave a Comment