表达式求值

给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值。

#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;
unordered_map <char, int> mp;
stack<int> nums;
stack<char> ops;

void init () {
    mp['('] = 0;
    mp['+'] = mp['-'] = 1;
    mp['*'] = mp['/'] = 2;
}

bool isd (char c) {
    return '0' <= c && c <= '9';
}

void cal () {
    char op = ops.top(); ops.pop();
    int b = nums.top(); nums.pop();
    int a = nums.top(); nums.pop();
    
    if (op == '+') nums.push(a + b);
    else if (op == '-') nums.push(a - b);
    else if (op == '*') nums.push(a * b);
    else nums.push(a / b);
} 

int main() {
    init();
    string s;
    cin >> s;
    for (int i = 0; i < s.size(); i++) {
        char c = s[i];
        if (isd(c)) {
            int j = i, x = 0;
            while (j < s.size() && isd(s[j])) x = x * 10 + s[j++] - '0';
            nums.push(x);
            i = --j;
        }
        else if (c == '(') ops.push(c);
        else if (c == ')') {
            while (ops.top() != '(') cal();
            ops.pop();
        }
        else {
            while (ops.size() && ops.top() != '(' && mp[ops.top()] >= mp[c]) cal();
            ops.push(c);
        }
    }
    
    while (ops.size()) cal();
    cout << nums.top() << endl;
    return 0;
}

  

posted @ 2022-11-30 21:58  !&&||  阅读(26)  评论(0)    收藏  举报