题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ #include <iostream> #include <stack> #include <cctype> int precedence(char op) { if (op == '+' || op == '-') return 1; if (op == '*') return 2; return 0; } int applyOperation(int a, int b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; default: return 0; // Handle other cases if needed } } int solve(const std::string& expression) { std::stack<int> numStack; std::stack<char> opStack; for (int i = 0; i < expression.length(); ++i) { if (std::isspace(expression[i])) continue; if (std::isdigit(expression[i])) { int num = 0; while (i < expression.length() && std::isdigit(expression[i])) { num = num * 10 + (expression[i] - '0'); ++i; } --i; numStack.push(num); } else if (expression[i] == '(') { opStack.push('('); } else if (expression[i] == ')') { while (opStack.top() != '(') { int b = numStack.top(); numStack.pop(); int a = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); numStack.push(applyOperation(a, b, op)); } opStack.pop(); // Pop '(' } else { while (!opStack.empty() && precedence(opStack.top()) >= precedence(expression[i])) { int b = numStack.top(); numStack.pop(); int a = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); numStack.push(applyOperation(a, b, op)); } opStack.push(expression[i]); } } while (!opStack.empty()) { int b = numStack.top(); numStack.pop(); int a = numStack.top(); numStack.pop(); char op = opStack.top(); opStack.pop(); numStack.push(applyOperation(a, b, op)); } return numStack.top(); } };