程式語言 - LeetCode - C++ - 150. Evaluate Reverse Polish Notation



題目:


解答:

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        int ans = 0;
        stack<int> st;

        auto is_op = [&](string s) -> bool {
            if (s == "+" || s == "-" || s == "*" || s == "/") {
                return true;
            }
            return false;
        };

        for (string s : tokens) {
            if (!is_op(s)) {
                st.push(stoi(s));
                continue;
            }

            int a = st.top(); st.pop();
            int b = st.top(); st.pop();

            if (s == "+") st.push(b + a);
            else if (s == "-") st.push(b - a);
            else if (s == "*") st.push(b * a);
            else if (s == "/") st.push(b / a);
        }

        return st.top();
    }
};