Sunday, December 31, 2017

Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +-*/. Each operand may be an integer or another expression.
Some examples:
  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int ans;
        stack<int> st;
       
        for (int i = 0; i < tokens.size(); i++) {
            if (tokens[i] != "+" && tokens[i] != "-" &&
                tokens[i] != "*" && tokens[i] != "/") {
                st.push(stoi(tokens[i]));
            } else {
                if (st.size() < 2) {
                    return -1;
                }
                int first = st.top(); st.pop();
                int second = st.top(); st.pop();
                int new_val;
                if (tokens[i] == "+") {
                    new_val = first + second;
                } else if  (tokens[i] == "-") {
                    new_val = second - first;
                } else if (tokens[i] == "*") {
                    new_val = first * second;
                } else {
                    new_val = second / first;
                }
                st.push(new_val);
            }
        }
        ans = st.top(); st.pop();
        return ans;
    }
};

No comments:

Post a Comment