表达式求值


题目链接:https://www.acwing.com/problem/content/3305/

题目解法

某个巨巨的题解 -> https://www.acwing.com/solution/content/40978/

代码

#include 
#include 
#include 
#include 
#include 

using namespace std;

stack num;
stack op;
unordered_map pr{{'+',1},{'-',1},{'*',2},{'/',2}};

void eval() {
    int res;
    int a = num.top();num.pop();
    int b = num.top();num.pop();
    char c = op.top();op.pop();
    
    if(c == '+') res = b + a;
    else if(c == '-') res = b - a;
    else if(c == '*') res = b * a;
    else res = b / a;
    
    num.push(res);
}

int main()
{
    string s;
    cin >> s;
    
    for (int i = 0 ; i < s.size() ; i ++ ) {
        char c = s[i];
        if(isdigit(c)) {
            int ans = 0,j;
            for (j = i ; isdigit(s[j]) ; j ++ ) {
                ans = ans * 10 + s[j] - '0';
            }
            i = j - 1;
            num.push(ans);
        }
        else if(c == '(') op.push(c);
        else if(c == ')') {
            while (op.top() != '(') eval();
            op.pop();
        }
        else {
            while (op.size() && pr[op.top()] >= pr[c]) eval();
            op.push(c);
        }
    }
    
    while(op.size()) eval();
    cout << num.top() << endl;
    return 0;
}