题解 | 四则运算

四则运算

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

#include <iostream>
#include <stack>
#include <string>
#include <cctype>

using namespace std;

void compute(stack<int>& st1, stack<char>& st2) {
    int b  = st1.top();
    st1.pop();
    int a = st1.top();
    st1.pop();
    char op = st2.top();
    st2.pop();
    if ( op == '+') a = a + b;
    else if (op == '-') a = a - b;
    else if ( op == '*') a = a * b;
    else if (op == '/') a = a / b;
    st1.push(a);
}
bool priority(char m, char n) {
    if (m == '(') return false;
    else if (( m == '+' ||  m == '-') && ( n == '*' || n == '/')) return false;
    return true;
}

int main() {
    string s;
    while (cin >> s) {
        stack<int> st1; //记录运算数字
        stack<char> st2; //记录运算符
        st2.push('('); //整个运算式添加括号
        s += ')';
        bool flag = false;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == '(' || s[i] == '[' ||
                    s[i] == '{') //如果是左括号都在运算符栈加入(
                st2.push('(');
            else if (s[i] == ')' || s[i] == ']' || s[i] == '}') { //遇到右括号
                while (st2.top() != '(') { //弹出开始计算直到遇到左括号
                    compute(st1, st2);
                }
                st2.pop(); //弹出左括号
            } else if (flag) {
                while (priority(st2.top(), s[i])) {
                    compute(st1, st2);
                }
                st2.push(s[i]);
                flag = false;
            } else {
                int j = i;
                if (s[j] == '-' || s[j] == '+') i++;
                while (isdigit(s[i])) i++;
                string temp = s.substr(j, i - j);
                st1.push(stoi(temp));
                i--;
                flag = true;
            }
        }
        cout << st1.top() << endl;
    }
    return 0;
}

全部评论

相关推荐

Beeee0927:是缅甸园区吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 12:10
点赞 评论 收藏
分享
06-13 10:15
门头沟学院 Java
想去夏威夷的大西瓜在...:我也是27届,但是我现在研一下了啥项目都没有呀咋办,哎,简历不知道咋写
点赞 评论 收藏
分享
06-26 22:20
门头沟学院 Java
码农索隆:让你把简历发给她,她说一些套话,然后让你加一个人,说这个人给你改简历,然后开始卖课
我的求职精神状态
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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