题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
#include <stdio.h> #include <string.h> /* 全局變量,使得內外層遞歸函數的線程都可以取用並操作 */ char str[101]; int i=0; /* 每次讀取到"+""-"的符號都記錄flag,並在下次讀取完數字後變號、入棧; 每次讀取到"*""/"的符號都記錄flag,並在下次讀取完數字後與當前棧頂層進行對應乘除操作、替換頂層棧; 每次讀取到"("的符號就進入下一層遞歸,將括號內的數字歸並計算、並考慮括號外的符號flag進行對應入棧操作; 讀取到")"或"\0"的符號則記錄當前讀取到的數字,並跳出循環,再計算當前遞歸層的數字、返回該值; 返回後的作為外層循環的最新數值,並考慮之前的符號flag、進行對應的入棧計算。 */ long int Solve(int length) { int top=-1; long int num=0, sum=0, stk[100]={0}; char sign_flag='+'; //記錄上一次讀取的符號 while (i<=length) { if (str[i]>='0' && str[i]<='9') { num = 10*num + (str[i]-'0'); } else { if (str[i]=='+' || str[i]=='-' || str[i]=='*' || str[i]=='/') { if (sign_flag=='+') stk[++top] = num; else if (sign_flag=='-') stk[++top] = (-1)*num; else if (sign_flag=='*') stk[top] *= num; else stk[top] /= num; num = 0; sign_flag = str[i]; } else { if (str[i]=='(') { i++; num = Solve(length); } else if (str[i]==')' || str[i]=='\0') { if (sign_flag=='+') stk[++top] = num; else if (sign_flag=='-') stk[++top] = (-1)*num; else if (sign_flag=='*') stk[top] *= num; else stk[top] /= num; num = 0; break; } } } i++; } for (int j=0; j<=top; j++) { sum += stk[j]; } return sum; } int main() { scanf("%s\n", str); int len=strlen(str); long int solveout=Solve(len); printf("%ld\n", solveout); return 0; }