题解 | #逆波兰表达式求值#

逆波兰表达式求值

https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382

#include <string>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        // write code here
        stack<int> st;
        int num1, num2;
        for (string & i : tokens)
        {
            if ((i != "+") && (i != "-") && (i != "*") && (i != "/"))
            {
                st.push(std::stoi(i));
            }
            else if (!st.empty())
            {
                num1 = st.top();
                st.pop();
                num2 = st.top();
                st.pop();
                if (i == "+")
                    st.push(num1 + num2);
                else if (i == "-")
                    st.push(num2 - num1);
                else if (i == "*")
                    st.push(num1 * num2);
                else if (i == "/")
                    st.push(num2 / num1);
            }
        }
        return st.top();
    }
};

全部评论

相关推荐

LemontreeN:有的兄弟有的我今天一天面了五场,4个二面一个hr面
投递字节跳动等公司7个岗位
点赞 评论 收藏
分享
06-13 17:00
武汉大学 Java
6月了还有点击就送的offer吗😭,投麻了😢
叫我阿东就行:这个bg,也还没找到理想的工作吗?好难,好焦虑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务