实现一个算法,可以进行任意非负整数的加减乘除组合四则运算。
请注意运算符的优先级。
输入:
输出:
示例:
输入:
3 + 5
12 + 45 / 9
1 / 2
1 / 0
12 + 34 * 56 - 78
输出:
8
17
0
err
1838
中缀表达式求值问题,中缀表达式就是我们自己所书写的表达式。后缀表达式也称逆波兰表达式,也是计算机所识别的表达式。
我们可以将表达式转化为初始的表达式树,这颗表达式树的中序遍历即为中缀表达式,表达式的后序遍历即为后序表达式。
表达式树的内部节点都是运算符,叶节点都是操作数,即数字。
中缀表达式需要括号来确定运算符优先级,而后缀表达式不需要,这也是后缀表达式应用于计算机计算的原因。
中缀表达式问题偏难,思维难度大,也是栈的经典应用。
代码实现:
#include
using namespace std;
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; // 可拓展,{'^', 3},在 cal() 函数中加相对应的运算定义即可
stack<char> op; // 经典双栈操作,符号栈、运算符栈
stack<int> num;
int flag = 1; // 用来判断是否为 除0异常
void cal() {
int b = num.top(); num.pop(); // 反着写,因为 a/b、a-b 的时候,栈顶先是 b,之后才是 a
int a = num.top(); num.pop();
auto c = op.top(); op.pop();
if (c == '+') num.push(a + b);
else if (c == '-') num.push(a - b);
else if (c == '*') num.push(a * b);
else {
if (b == 0) {
flag = 0;
num.push(0);
}
else
num.push(a / b);
}
}
// 整个代码中没有涉及运算符的直接操作,采用 cal() 函数封装的形式完成,可扩展性强
int main() {
string str;
getline(cin, str);
string s;
while (str.size()) {
int n = str.find(' ');
if (n == -1) {
break;
}
s += str.substr(0, n);
str = str.substr(n + 1);
}
s += str;
for (int i = 0; i < s.size(); ++i) {
auto c = s[i];
if (c >= '0' && c <= '9') {
int x = 0, j = i;
while (j < s.size() && s[j] >= '0' && s[j] <= '9') x = x * 10 + s[j++] - '0';
i = j - 1; // 别忘记更新 i,跳过这个数字
num.push(x);
}
else {
while (op.size() && pr[op.top()] >= pr[c]) cal(); // 在本题中,这个while最多执行两次,所以改成两个if也可以过
op.push(c);
}
}
while (op.size()) cal(); // 最后操作剩余的符号
if (flag) cout << num.top() << endl;
else cout << "err" << endl;
return 0;
}
链接:3302.表达式求值
代码实现:
#include
#include
#include
#include
#include
using namespace std;
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; // 可拓展,{'^', 3},在 cal() 函数中加相对应的运算定义即可
stack<char> op; // 经典双栈操作,符号栈、运算符栈
stack<int> num;
void cal() {
int b = num.top(); num.pop(); // 反着写,因为 a/b、a-b 的时候,栈顶先是 b,之后才是 a
int a = num.top(); num.pop();
auto c = op.top(); op.pop();
if (c == '+') num.push(a + b);
else if (c == '-') num.push(a - b);
else if (c == '*') num.push(a * b);
else num.push(a / b);
}
// 整个代码中没有涉及运算符的直接操作,采用 cal() 函数封装的形式完成,可扩展性强
int main() {
string s;
cin >> s;
for (int i = 0; i < s.size(); ++i) {
auto c = s[i];
if (c >= '0' && c <= '9') {
int x = 0, j = i;
while (j < s.size() && s[j] >= '0' && s[j] <= '9') x = x * 10 + s[j++] - '0';
i = j - 1; // 别忘记更新 i,跳过这个数字
num.push(x);
}
else if (c == '(') op.push(c); // 左括号直接入栈
else if (c == ')') {
while (op.top() != '(') cal(); // 右括号的话,从栈顶开始操作运算符,直到找到左括号为止。从栈顶开始,就是从右向左操作
op.pop(); // 左括号出栈
}
else {
while (op.size() && pr[op.top()] >= pr[c]) cal(); // 在本题中,这个while最多执行两次,所以改成两个if也可以过
op.push(c);
}
}
while (op.size()) cal(); // 最后操作剩余的符号
cout << num.top() << endl;
return 0;
}