题解 | #计算表达式#

计算表达式

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

#include <iostream>
#include <cstdio>
#include <string>
#include <stack>
#include <map>
using namespace std;

void Calculate(stack<double>& num, char oper) {//根据传入数据计算结果
    double right = num.top();
    num.pop();
    double left = num.top();
    num.pop();
    double ret = 0;
    switch (oper) {
        case '+':
            ret = left + right;
            break;
        case '-':
            ret = left - right;
            break;
        case '*':
            ret = left * right;
            break;
        case '/':
            ret = left / right;
            break;
    }
    num.push(ret);
}

double isNumber(char count) { //转换传入字符,不是数字输出-1
    if ('0' <= count && count <= '9') {
        return count - '0';
    } else {
        return -1;
    }
}

double assembleNumber(string exp, int& i) {
    double data = 0;
    while (isNumber(exp[i]) != -1) {
        data = data * 10 + exp[i++] - '0';
    }
    return data;
}

int main() {
    char str[101];
    map<char, int> prior = { //记录各符号优先级
        {'$', 0},
        {'+', 1}, {'-', 1},
        {'*', 2}, {'/', 2},
    };
    while (scanf("%s", str) != EOF) {
        string exp = str;
        stack<double> num;
        stack<char> oper;
        exp.push_back('$');//终止标志
        for (int i = 0; i < exp.size();) { //遍历表达式
            if (isNumber(exp[i]) != -1) {
                num.push(assembleNumber(exp, i));
            } else {
                while (!oper.empty() && prior[oper.top()] >= prior[exp[i]]) {
                    Calculate(num, oper.top());
                    oper.pop();//使用过该符号后弹出栈
                }
                oper.push(exp[i++]);//此时的符号入栈
            }
        }
        printf("%.0f\n", num.top());
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

07-01 19:00
门头沟学院 Java
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
06-23 11:28
门头沟学院 Java
牛客91966197...:也有可能是点拒绝的时候自动弹的话术
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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