提交时间:2024-08-21 12:57:53
运行 ID: 180025
#include<iostream> #include<string> #include<map> #include<stack> using namespace std; stack<int> num; stack<char> op; void eval(){ int b = num.top(); num.pop(); int a = num.top(); num.pop(); char c = op.top(); op.pop(); int x; if(c == '+') x = a + b; else if(c == '-') x = a - b; else if(c == '*') x = a * b; else x = a / b; num.push(x); } int main(){ string s; cin >> s; map<char, int> mp = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; for(int i = 0; i < s.size(); i++){ if(isdigit(s[i])){ int j = i, operand = 0; while(j < s.size() && isdigit(s[j])){ operand = operand * 10 + s[j] - '0'; j++; } num.push(operand); i = j - 1; }else if(s[i] == '('){ op.push(s[i]); }else if(s[i] == ')'){ while(op.top() != '(') eval(); op.pop(); }else{ while(op.size() && op.top() != '(' && mp[op.top()] >= mp[s[i]]) eval(); op.push(s[i]); } } while(op.size()) eval(); cout << num.top() << endl; return 0; }