C++ Solution using stack
class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        
        if (tokens.size() == 1) {
            return stoi(tokens[0]);
        }
        stack<int> si;
        set<string> ss = {"+", "-", "*", "/"};
        int n1=0, n2=0;
        for (int i=0; i<tokens.size(); i++) {
            if (si.size() >= 2 && ss.find(tokens[i]) != ss.end()) {
                n2 = si.top();
                si.pop(); 
                n1 = si.top();
                si.pop();
            }
            if (tokens[i] == "+") {
                int tmp = n1+n2;
                si.push(tmp);
            }
            else if (tokens[i] == "-") {
                int tmp = n1-n2;
                si.push(tmp);
            }
            else if (tokens[i] == "*") {
                int tmp = n1*n2;
                si.push(tmp);
            }
            else if (tokens[i] == "/"){
                if (n2 == 0) {
                    throw runtime_error("dividedby0");
                }
                int tmp = n1/n2;
                si.push(tmp);
            }
            else {
                si.push(stoi(tokens[i]));    
            }
        }
        return si.top();
        
    }
};
Comments (0)