You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
38 lines
1.1 KiB
38 lines
1.1 KiB
#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)); //"24"-->24
|
|
}
|
|
return stk.top();
|
|
}
|
|
|
|
int main() {
|
|
string s = "24 9 6 3 / + 5 - * 4 +";
|
|
cout << "answer: " << eval(s) << endl;
|
|
return 0;
|
|
}
|
|
/*
|
|
中缀表达式: (24*(9+6/3-5)+4)
|
|
后缀表达式: 24 9 6 3 / + 5 - * 4 +
|
|
值=148
|
|
*/ |