题目
题解
#include<iostream>
#include<unordered_map>
#include<stack>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char, int> cmp = {
{'+', 1}, {'-', 1} , {'*', 2}, {'/', 2}
};
void eval(void){
int b = num.top(); num.pop();
int a = num.top(); num.pop();
char opr = op.top(); op.pop();
int x;
if(opr == '+') x = a + b;
else if(opr == '-') x = a - b;
else if(opr == '*') x= a * b;
else x = a / b;
num.push(x);
}
int main(){
string str;
cin >> str;
for(int i = 0; i < str.size(); i++){
char c = str[i];
if(isdigit(c)){
int j = i, x = 0;
while( j < str.size() && isdigit(str[j])){
x = x * 10 + str[j ++] - '0';
}
num.push(x);
i = j - 1;
}else if( c == '(' ){
op.push(c);
}else if( c == ')' ){
while( op.size() && op.top() != '(' ) eval();
op.pop();
}else{
while( op.size() && cmp[op.top()] >= cmp[c]) eval();
op.push(c);
}
}
while(op.size()) eval();
cout << num.top() << endl;
return 0;
}