题解 | #四则运算# C++ 双栈

四则运算

https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

#include <iostream>
#include <stack>
using namespace std;

void compute(stack<int>& num_st, stack<char>& op_st) {
    int op2 = num_st.top();
    num_st.pop();
    int op1 = num_st.top();
    num_st.pop();
    char op = op_st.top();
    op_st.pop();
    if (op == '+') op1 += op2;
    if (op == '-') op1 -= op2;
    if (op == '*') op1 *= op2;
    if (op == '/') op1 /= op2;
    num_st.push(op1);
}

bool priority(char m, char n) {
    // m 优先级小于n, 返回true
    if (m == '(' || m == '[' || m == '{') {
        return false;
    }
    if ((n == '+' || n == '-') && (m == '*' || m == '/')) {
        return false;
    }
    return true;
}

int main() {
    string str;
    cin >> str;
    stack<int> num_st;
    stack<char> op_st;
    str.push_back('}');
    op_st.push('{');
    bool isOp = false;
    for (int i = 0; i < str.size(); ++i) {
        // 碰到右括号
        if (str[i] == '}' || str[i] == ']' || str[i] == ')') {
            string leftkuo = "([{";
            while (leftkuo.find(op_st.top()) == leftkuo.npos) {
                compute(num_st, op_st);
            }
            op_st.pop(); // 弹出左括号
        } else if (str[i] == '{' || str[i] == '[' || str[i] == '(') {
            op_st.push(str[i]);
        } else if (isOp) {
            // 栈内操作符优先级大,先计算栈内
            while (priority(str[i], op_st.top()) &&
                op_st.top() != '(' && op_st.top() != '[' && op_st.top() != '{') {
                compute(num_st, op_st);
            }
            op_st.push(str[i]);
            isOp = false;
        } else {
            int start = i;
            if (str[i] == '+' || str[i] == '-') {
                i++;
            }
            while (i < str.size() && isdigit(str[i])) i++;
            num_st.push(stoi(str.substr(start, i - start)));
            --i;
            isOp = true;
        }
    }
    cout << num_st.top() << endl;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 11:35
程序员小白条:话太多,没实力和学历,差不多回答回答就行了,身份地位不一样
点赞 评论 收藏
分享
06-25 16:25
梧州学院 Java
愿汐_:项目介绍那么长,然而你做了啥就一句话?
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 12:31
以前小时候我最痛恨出轨、偷情的人,无论男女,为什么会出轨?现在我成了自己最讨厌的人,没想到分享的东西在牛客会被这么多人看,大家的评价都很中肯,我也认同,想过一一回复,但我还是收声了,我想我应该说说这件事,这件事一直压在我心里,是个很大的心结,上面说了人为什么出轨,我大概能明白了。我们大一下半年开始恋爱,开始恋爱,我给出了我铭记3年的承诺,我对她好一辈子,我永远不会背叛,我责任心太重,我觉得跟了我,我就要照顾她一辈子,我们在一起3年我都没有碰过她,她说往东我就往东,她说什么我做什么,她要我干什么,我就干什么!在学校很美好,中途也出过一些小插曲,比如男闺蜜、男闺蜜2号等等等。但我都强迫她改掉了,我...
牛客刘北:两个缺爱的人是没有办法好好在一起的,但世界上哪有什么是非对错?你后悔你们在一起了,但是刚刚在一起的美好也是真的呀,因为其他人的出现,你开始想要了最开始的自己,你的确对不起自己,21岁的你望高物远,你完全可以不谈恋爱,去过你想要的生活,你向往自由,在一起之后,你要想的不是一个人,而是两个人,你不是变心了,就像你说的,你受够了,你不想包容了,冷静几天是你最优的选择,爱人先爱己。
社会教会你的第一课
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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