题解 | 牛牛与后缀表达式,注意记录数字的时候不要把加减乘符号算进去了,其次switch的顺序有讲究

牛牛与后缀表达式

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

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 给定一个后缀表达式,返回它的结果
     * @param str string字符串 
     * @return long长整型
     */
    long long legalExp(string str) {
        // write code here
        vector<long long> a;
        long long index = -1;
        long long res;
        for (int i =0; i<str.size(); i++) {
            switch (str[i]) {
                case '+':
                    res = a[a.size()-2] + a[a.size()-1];
                    a.pop_back();
                    a.pop_back();
                    a.push_back(res);
                    cout<<res<<endl;
                    index = i;
                    break;
                case '-':
                    res = a[a.size()-2] - a[a.size()-1];
                    a.pop_back();
                    a.pop_back();
                    a.push_back(res);
                    cout<<res<<endl;
                    index = i;
                    break;
                case '*':
                    res = a[a.size()-2] * a[a.size()-1];
                    a.pop_back();
                    a.pop_back();
                    a.push_back(res);
                    cout<<res<<endl;
                    index = i;
                    break;
                case '#':
                    string numstr;
                    for (int j=index+1; j<i; j++) {
                        numstr.push_back(str[j]);
                    }
                    a.push_back(stoi(numstr));
                    index = i;
                    cout<<stoi(numstr)<<endl;
                    break;
            }
        }
        return a[0];
    }
};

为啥把‘#’放在最前面后面的所有case都会报错呢?

全部评论

相关推荐

03-15 10:59
已编辑
美团_后端开发(实习员工)
爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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