1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include <bits/stdc++.h> using namespace std;
int main(){ int n;cin>>n; string s; while(n--){ cin>>s; stack<int> stk; bool legal = 1; for(int i=0;i<s.size();i++){ if(s[i]==')'||s[i]==','||s[i]=='('); else if(isdigit(s[i])){ int sum = s[i]-'0'; while(isdigit(s[++i])){ sum=sum*10+(s[i]-'0'); } stk.push(sum); i--; } else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){ if(s[i+1]!=')'){ legal = 0; break; } int a = stk.top(); stk.pop(); int b = stk.top(); stk.pop(); if(s[i]=='+')stk.push(a+b); else if(s[i]=='-')stk.push(b-a); else if(s[i]=='*')stk.push(a*b); else if(s[i]=='/'&& a==0){ legal = 0; break; } else if(s[i]=='/')stk.push(b/a); } else{ legal = 0; break; } } if(legal==0)cout<<-1<<endl; else if(stk.size()==1)cout<<stk.top()<<endl; else cout<<-1<<endl; } }
|