题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
#include <stdio.h> #include <string.h> int pos = 0; int findnul(char *str){ int nul = 0; for(int i = 0; str[i]; i++){ if(str[i] >= '0' && str[i] <= '9'){ nul = nul * 10 + str[i] - '0'; pos++; } else return nul; } return nul; } int resurt(char *str){ int sum = 0; int tmp = 0; char flag = '+'; int nul[200]; int nul_top = 0; while(str[pos] != '\0'){ if(str[pos] == '+' || str[pos] == '-' || str[pos] == '*' || str[pos] == '/'){ flag = str[pos]; pos++; } if(str[pos] == '(' || str[pos] == '{' || str[pos] == '['){ pos++; tmp = resurt(str); } else tmp = findnul(str + pos); switch(flag){ case '+' : nul[nul_top++] = tmp; break; case '-' : nul[nul_top++] = -tmp; break; case '*' : nul[nul_top - 1] *= tmp; break; case '/' : nul[nul_top - 1] /= tmp; break; } if(str[pos] == ')' || str[pos] == '}' || str[pos] == ']'){ pos++; break; } } for(int i = 0; i < nul_top; i++){ sum += nul[i]; } return sum; } int main(){ char str[1002]; fgets(str, sizeof(str), stdin); str[strlen(str) - 1] = '\0'; int len = strlen(str); printf("%d", resurt(str)); return 0; }