题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
#include<iostream> #include<sstream> #include<stack> using namespace std; void inStack(stack<double>& st, char ch, double value){ if(ch=='+'){ st.push(value); } else if(ch == '-'){ st.push(-value); } else if(ch == '*'){ double a=st.top(); st.pop(); st.push(a*value); } else{ double a=st.top(); st.pop(); st.push(a/value); } } double calculate(string s){ stack<double> st; st.push(0); char ch = '+'; stack<char> st_ch; int i=0, len = s.length(); while(i<len){ if(isdigit(s[i])){ double num = 0; int j=i; while(j<len&&isdigit(s[j])){ num = num*10+(s[j]-'0'); j++; } i=j-1; inStack(st, ch, num); } else if(s[i]=='{'||s[i]=='['||s[i]=='('){ st_ch.push('('); int j=i; while(j<len&&st_ch.size()!=0){ j++; if(s[j]==')'||s[j]=='}'||s[j]==']'){ st_ch.pop(); } else if(s[j]=='{'||s[j]=='['||s[j]=='('){ st_ch.push('('); } } string temp = s.substr(i+1, j-i-1); double value = calculate(temp); inStack(st, ch, value); i = j; } else{ ch = s[i]; } i++; } double ans = 0; while(!st.empty()){ ans+=st.top(); st.pop(); } return ans; } int main(){ string s; while(cin>>s){ double ans = calculate(s); cout<<ans<<endl; } }