150. 逆波兰表达式求值

给你一个字符串数组 tokens ,表示一个根据 逆波兰表示法 表示的算术表达式。

请你计算该表达式。返回一个表示表达式值的整数。

注意:

有效的算符为 '+'、'-'、'*' 和 '/' 。
每个操作数(运算对象)都可以是一个整数或者另一个表达式。
两个整数之间的除法总是 向零截断 。
表达式中不含除零运算。
输入是一个根据逆波兰表示法表示的算术表达式。
答案及所有中间计算结果可以用 32 位 整数表示。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        for (auto cur = tokens.cbegin(); cur != tokens.cend(); cur++)
        {
            int t1,t2;
            t1 = sta.top();
            sta.pop();
            t2 = sta.top();
            sta.pop();
            if(*cur=="+")
            {
                sta.push(t1 + t2);
            }
            else if(*cur=="-")
            {
                sta.push(t2 - t1);
            }
            else if(*cur=="*")
            {
                sta.push(t1 * t2);
            }
            else if(*cur=="/")
            {
                sta.push(t2 / t1);
            }
            else{
                sta.push(atoi((*cur).c_str()));
            }
        }
        int res = sta.top();
        return res;
    }
private:
    std::stack<int> sta;
};
posted @ 2023-03-27 20:48  xiazichengxi  阅读(19)  评论(0)    收藏  举报