题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
#include <stdio.h> #include <string.h> int main() { int map[127] = { 0 }; map['+'] = 1; map['-'] = 1; map['*'] = 2; map['/'] = 2; char str[101] = { 0 }; int a1[101] = { 0 }; char a2[101] = { 0 }; scanf("%s", str); int len = strlen(str); char str2[201] = { 0 }; int c = 0; int i = 0; int j = 0; strcpy(&str2[1], str); str2[0] = '('; str2[len+1] = ')'; for (int k = 0; k < len + 2; k++) { if (str2[k] == '-' && str2[k - 1] == '(') { memmove(&str2[k + 1], &str2[k], len + 2 - k); len++; str2[k] = '0'; } } while (c < len + 2) { if (str2[c] >= '0' && str2[c] <= '9') { int n = 0; char std[12] = { 0 }; int m = 0; while (str2[c] >='0'&&str2[c]<='9') { std[m++] = str2[c++]; } int lenc = m - 1; for (m = 0; m <=lenc; m++) { n = n * 10 + (std[m] - '0'); } a1[i++] = n; } else if (map[str2[c]] > map[a2[j-1]] && str2[c] != '(') { a2[j++] = str2[c++]; } else if (map[str2[c]] <= map[a2[j-1]] && str2[c] != '(' && str2[c] != ')') { int n = 0; if (a2[j - 1] == '+') n = a1[i - 2] + a1[i - 1]; if (a2[j - 1] == '-') n = a1[i - 2] - a1[i - 1]; if (a2[j - 1] == '*') n = a1[i - 2] * a1[i - 1]; if (a2[j - 1] == '/') n = a1[i - 2] / a1[i - 1]; a1[i - 2] = n; a1[i - 1] = 0; a2[j - 1] = 0; j = j - 1; i = i - 1; } else if (str2[c] == '(') { a2[j++] = str2[c++]; } else { if (str2[c] == ')' && a2[j - 1] == '(') { a2[j - 1] = 0; j = j - 1; c++; } else { int n = 0; if (a2[j - 1] == '+') n = a1[i - 2] + a1[i - 1]; if (a2[j - 1] == '-') n = a1[i - 2] - a1[i - 1]; if (a2[j - 1] == '*') n = a1[i - 2] * a1[i - 1]; if (a2[j - 1] == '/') n = a1[i - 2] / a1[i - 1]; a1[i - 2] = n; a1[i - 1] = 0; a2[j - 1] = 0; j = j - 1; i = i - 1; } } } printf("%d\n", a1[0]); return 0; }