solution.cpp 965 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
int evalRPN(vector<string> &tokens)
{
    stack<int> sp;
    int n = tokens.size();
    for (int i = 0; i < n; i++)
    {
        if (tokens[i] == "+")
        {
            int x = sp.top();
            sp.pop();
            int y = sp.top();
            sp.pop();
            sp.push(x + y);
        }
        else if (tokens[i] == "-")
        {
            int x = sp.top();
            sp.pop();
            int y = sp.top();
            sp.pop();
            sp.push(y - x);
        }
        else if (tokens[i] == "*")
        {
            int x = sp.top();
            sp.pop();
            int y = sp.top();
            sp.pop();
            sp.push(x * y);
        }
        else if (tokens[i] == "/")
        {
            int x = sp.top();
            sp.pop();
            int y = sp.top();
            sp.pop();
            sp.push(y / x);
        }
        else
        {
            sp.push(stoi(tokens[i]));
        }
    }
    return sp.top();
}