题解 | #计算表达式#

计算表达式

https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

#include <bits/stdc++.h>
#include <cctype>
#include <stack>
using namespace std;
map<char, int> m;
stack<double> shuzi;
stack<char> op;//运算符
void cal(double a, double b, char opp) {
    if (opp == '+') shuzi.push(b + a);
    if (opp == '-') shuzi.push(b - a);
    if (opp == '*') shuzi.push(b * a);
    if (opp == '/') shuzi.push(b / a);
}
int main() {
    m.insert(make_pair('+', 1));
    m.insert(make_pair('-', 1));
    m.insert(make_pair('*', 2));
    m.insert(make_pair('/', 2));
    string s;
    while (cin >> s) {
        for (int i = 0; i < s.length();) {
            if (isdigit(s[i])) {
                string num = "";
                while (i < s.length() && isdigit(s[i])) {
                    num += s[i];
                    i++;
                }
                shuzi.push(stoi(num));
            } else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
                if (op.empty() || m[op.top()] < m[s[i]]) {
                    op.push(s[i]);
                } else {
                    while (!op.empty() && m[op.top()] >= m[s[i]]) {
                        char opp = op.top();
                        op.pop();
                        double a = shuzi.top();
                        shuzi.pop();
                        double b = shuzi.top();
                        shuzi.pop();
                        cal(a,b,opp);
                    }
                    op.push(s[i]);
                }
                i++;
            }
        }
        while (!op.empty()) {
            char opp = op.top();
            op.pop();
            double a = shuzi.top();
            shuzi.pop();
            double b = shuzi.top();
            shuzi.pop();
            cal(a,b,opp);
        }
        cout << shuzi.top();
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

07-02 22:46
门头沟学院 Java
码农索隆:hr:“管你投没投,先挂了再说”
点赞 评论 收藏
分享
点赞 评论 收藏
分享
07-18 14:03
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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