题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
#include <stdio.h> #include <stdlib.h> #include <string.h> int getPriority(char op) { if (op == '+' || op == '-') return 1; if (op == '*' || op == '/') return 2; if (op == '(') return 0; return 0; } int calculate(int a, int b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: return 0; } } int solve(char* s) { int len = strlen(s); int values[len]; int valIndex = 0; char operators[len]; int opIndex = -1; for (int i = 0; i < len; i++) { if (s[i] >= '0' && s[i] <= '9') { int val = 0; while (i < len && s[i] >= '0' && s[i] <= '9') { val = val * 10 + (s[i] - '0'); i++; } i--; values[valIndex++] = val; } else if (s[i] == '(') { operators[++opIndex] = s[i]; } else if (s[i] == ')') { while (opIndex >= 0 && operators[opIndex] != '(') { int b = values[--valIndex]; int a = values[--valIndex]; values[valIndex++] = calculate(a, b, operators[opIndex--]); } opIndex--; // 弹出 '(' } else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') { while (opIndex >= 0 && getPriority(operators[opIndex]) >= getPriority(s[i])) { int b = values[--valIndex]; int a = values[--valIndex]; values[valIndex++] = calculate(a, b, operators[opIndex--]); } operators[++opIndex] = s[i]; } } while (opIndex >= 0) { int b = values[--valIndex]; int a = values[--valIndex]; values[valIndex++] = calculate(a, b, operators[opIndex--]); } return values[0]; }