题解 | 牛牛与后缀表达式

牛牛与后缀表达式

https://www.nowcoder.com/practice/a1a4f178f6ff4188890e51da1cc8ce10

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 给定一个后缀表达式,返回它的结果
     * @param str string字符串 
     * @return long长整型
     */
    long long legalExp(string str) {
        // write code here
        stack<long long> stk;
        long long n=0,a=0,b=0;
        for(char i : str){
            if(i>='0'&&i<='9'){
                n=i-'0'+n*10;
            }else if(i=='#'){
                stk.push(n);
                n=0;
            }else if(i=='+'){
                a=stk.top();
                stk.pop();
                b=stk.top();
                stk.pop();
                stk.push(a+b);
            }else if(i=='-'){
                a=stk.top();
                stk.pop();
                b=stk.top();
                stk.pop();
                stk.push(b-a);
            }else if(i=='*'){
                a=stk.top();
                stk.pop();
                b=stk.top();
                stk.pop();
                stk.push(a*b);
            }
        }
        return stk.top();
    }};

全部评论

相关推荐

27届学院本誓死冲击...:自我评价和校园经历全删了,荣誉经历只留奖学金,项目也全得换都不如外卖
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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