题解 | #计算表达式#

计算表达式

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

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

typedef pair<int, char> pai;
map<char, int> m; //记录优先级

int main() {
    string str;
    m['+'] = 1, m['-'] = 1, m['*'] = 2, m['/'] = 2;
    while (cin >> str) {
        stack<pai> s;//存储运算符
        stack<double> num;//存储运算数
        for (int i = 0; i < str.size(); i++) {
            if (isdigit(str[i])) {
                int j = i;
                while (j < str.size() && isdigit(str[j])) j++;
                //i~j-1是一个数
                double k = 0;
                for (int t = i; t < j; t++) k = 10 * k + (str[t] - '0');
                num.push(k);

                i=j-1;
            } else {
                while (!s.empty() && s.top().first >= m[str[i]]) {
                    char op = s.top().second;
                    s.pop();
                    double y = num.top();
                    num.pop();
                    double x = num.top();
                    num.pop();
                    if (op == '+') num.push(x + y);
                    else if (op == '-') num.push(x - y);
                    else if (op == '*') num.push(x * y);
                    else num.push(x / y);
                }
                s.push({m[str[i]], str[i]});
            }
        }
        while (!s.empty()) {
            char op = s.top().second;
            s.pop();
            double y = num.top();
            num.pop();
            double x = num.top();
            num.pop();
            if (op == '+') num.push(x + y);
            else if (op == '-') num.push(x - y);
            else if (op == '*') num.push(x * y);
            else num.push(x / y);
        }
        cout<<num.top()<<endl;
    }
    return 0;
}

全部评论

相关推荐

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