题解 | #计算表达式#

计算表达式

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")

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务