题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
#include <stdio.h> #include <string.h> #include <ctype.h> int i = 0; int calculate(char* a) { int len = strlen(a); int stack[100] = { 0 }; int i_stack = 0; int flag = '+'; while (i < len) { int n = 0; if (a[i] == '(' || a[i] == '[' || a[i] == '{') { i++; n = calculate(a); } while (isdigit(a[i]) && i < len) { n = n * 10 + a[i++] - '0'; } switch (flag) { case '+': stack[i_stack++] = n; break; case '-': stack[i_stack++] = -n; break; case '*': stack[i_stack - 1] *= n; break; case '/': stack[i_stack - 1] /= n; break; } if (a[i] == ')' || a[i] == ']' || a[i] == '}') { i++; break; } flag = a[i++]; } int sum = 0; for (int j = 0; j < i + 1; j++) sum += stack[j]; return sum; } int main() { char arr[100] = { 0 }; scanf("%s", &arr); int i = 0; int n = calculate(arr); printf("%d\n", n); return 0; }