题解 | 计算表达式
计算表达式
https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b
#include <iostream>
#include <stdio.h>
#include <map>
#include <stack>
#include <string>
#include <string.h>
using namespace std;
int main() {
char str[1000] = { 0 };
map<char, int> priority = {
{'\0', 0},
{'-', 1}, {'+', 1},
{'*', 2}, {'/', 2}
};//用来记录运算的优先级
while (scanf("%s", str) != EOF) {
string numStr = "";
stack<double> numStack;
stack<char> opStack;
for (int i = 0;; i++) {
if (str[i] >= '0' && str[i] <= '9') {
numStr.push_back(str[i]);
} else {
if (!numStr.empty()) {
double num = stod(numStr);
numStr = "";
numStack.push(num);
}
// 什么时候弹栈 ? 栈非空 &&新op的优先级 不高于栈顶的优先级
// 循环弹栈或者计算
while (!opStack.empty() && priority[str[i]] <= priority[opStack.top()]) {
double rhs = numStack.top();
numStack.pop();
double lhs = numStack.top();
numStack.pop();
char curOp = opStack.top();
opStack.pop();
if (curOp == '+') {
numStack.push(lhs + rhs);
} else if (curOp == '*') {
numStack.push(lhs * rhs);
} else if (curOp == '/') {
numStack.push(lhs / rhs);
} else if (curOp == '-') {
numStack.push(lhs - rhs);
}
}
//离开了循环 栈为空或者新op优先级高于栈顶
if (str[i] == '\0') {
printf("%d\n", (int)numStack.top());
break;
} else {
opStack.push(str[i]);
}
}
}
}
return 0;
}