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.

75 lines
2.0 KiB

#include <bits/stdc++.h>
using namespace std;
stack<int> num; // 数字栈
stack<char> op; // 操作符栈
// 优先级表
unordered_map<char, int> h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'(', 0}};
/**
* 功能:计算两个数的和差积商
*/
void eval() {
int a = num.top(); // 第二个操作数
num.pop();
int b = num.top(); // 第一个操作数
num.pop();
char p = op.top(); // 运算符
op.pop();
int r; // 结果
// 计算结果
if (p == '+')
r = b + a;
else if (p == '-')
r = b - a;
else if (p == '*')
r = b * a;
else if (p == '/')
r = b / a;
// 结果入栈
num.push(r);
}
int main() {
// 读入表达式
string s;
cin >> s;
// 遍历字符串的每一位
for (int i = 0; i < s.size(); i++) {
// ① 如果是数字,则入栈
if (isdigit(s[i])) {
// 读出完整的数字
int x = 0;
while (i < s.size() && isdigit(s[i])) {
x = x * 10 + s[i] - '0';
i++;
}
i--; // 加多了一位,需要减去
num.push(x); // 数字入栈
}
// ② 左括号无优先级,入栈
else if (s[i] == '(')
op.push(s[i]);
// ③ 右括号时,需计算最近一对括号里面的值
else if (s[i] == ')') {
// 从栈中向前找,一直找到左括号
while (op.top() != '(') eval(); // 将左右括号之间的计算完,维护回栈里
// 左括号出栈
op.pop();
} else { // ④ 运算符
// 如果待入栈运算符优先级低,则先计算
while (op.size() && h[op.top()] >= h[s[i]]) eval();
op.push(s[i]); // 操作符入栈
}
}
while (op.size()) eval(); // ⑤ 剩余的进行计算
printf("%d\n", num.top()); // 输出结果
return 0;
}