Files
python/TangDou/CSP-J/J2_2020/ZhuanTi_BiaoDaShi/ToPostFix/TD.cpp

30 lines
741 B
C++
Raw Normal View History

2025-08-30 18:35:01 +08:00
#include <bits/stdc++.h>
using namespace std;
bool isOp(string c){
return c == "+" || c == "-" || c == "*" || c == "/";
}
int eval(string s){
stack<int> stk;
stringstream s1(s);
string c;
while (s1>>c){
if(isOp(c)){
int a = stk.top();
stk.pop();
int b = stk.top();
stk.pop();
if (c == "+") stk.push(b + a);
if (c == "-") stk.push(b - a);
if (c == "*") stk.push(b * a);
if (c == "/") stk.push(b / a);
}else
stk.push(stoi(c));
}
return stk.top();
}
int main() {
string s = "24 9 6 3 / + 5 - * 4 +";
cout << "answer:" << eval(s) << endl;
return 0;
}