Leetcode 150 Solution

This article provides solution to leetcode question 150 (evaluate-reverse-polish-notation)

https://leetcode.com/problems/evaluate-reverse-polish-notation

Solution

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> s;

        for (auto it = tokens.begin(); it != tokens.end(); it++)
        {
            string ch = *it;

            if (ch == "+" || ch == "-" || ch == "*" || ch == "/")
            {
                int b = s.top();
                s.pop();

                int a = s.top();
                s.pop();

                if (ch == "+")
                    s.push(a + b);
                else if (ch == "-")
                    s.push(a - b);
                else if (ch == "*")
                    s.push(a * b);
                else if (ch == "/")
                    s.push(a / b);
            }
            else
            {
                int a = atoi(it->c_str());
                s.push(a);
            }
        }

        return s.top();
    }
};