题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
计算通用
#include <stdio.h> #include <string.h> #include <stdlib.h> static int i = 0; static int compate(char *str) { if(!str) { return -1; } int stack[1000] = {0}; int top = -1; int len = strlen(str); //printf("str:[%s : %d]\n", str, len); char flag = '+'; //默认'+’号 while(i < len) { int num = 0; if(str[i] == '-') { i++; flag = '-'; } if(str[i] == '(') { i++; num = compate(str); } while(str[i] >= '0' && str[i] <= '9') { num = num*10 + (str[i]-'0'); i++; } switch(flag) { case '+': { stack[++top] += num; } break; case '-': { stack[++top] -= num; } break; case '*': { stack[top] *= num; } break; case '/': { stack[top] /= num; } break; default: break; } flag = str[i]; if(str[i] == ')') { i++; break; } i++; } int res = 0; for(int j = 0; j <= top; j++) { res += stack[j]; } return res; } int main() { char str[1000] = {0}; gets(str); int res = compate(str); printf("%d\n", res); return 0; }