1 solutions
-
0
C++ :
#include<iostream> #include<stack> #include<cstring> #include<cstdio> using namespace std; string s; stack<int> number; stack<char> symbol; int get_pre(char,bool); bool is_operator(char); void my_calc(); void work(); int main() { //freopen("test.in","r",stdin); //freopen("test.out","w",stdout); cin>>s; work(); return 0; } bool is_operator(char ch) { if(ch=='+'||ch=='-'||ch=='*'||ch=='/'||ch==')'||ch=='(')return true; else return false; } int get_pre(char ch,bool flag) { if(ch=='+'||ch=='-')return 1; if(ch=='/'||ch=='*')return 2; if(ch=='('&&flag)return 0; if(ch=='('&&!flag)return 3; return 4; } void my_calc() { int y=number.top(); number.pop(); if(symbol.top()=='+') number.top()+=y; if(symbol.top()=='-') number.top()-=y; if(symbol.top()=='*') number.top()*=y; if(symbol.top()=='/') number.top()/=y; symbol.pop(); } void work() { int i=0; while(i<s.size()) { if(!is_operator(s[i])) { int x=0; while(i<s.size()&&!is_operator(s[i])) { x=x*10+s[i]-48; i++; } number.push(x); continue; } if(s[i]=='(') { symbol.push(s[i]); i++; continue; } if(s[i]==')') { while(symbol.top()!='(') { my_calc(); } symbol.pop(); ++i; continue; } while(!symbol.empty()&&get_pre(s[i],false)<=get_pre(symbol.top(),true)) { my_calc(); } symbol.push(s[i]); i++; } while(!symbol.empty()) { my_calc(); } cout<<number.top()<<endl; }
- 1
Information
- ID
- 527
- Time
- 1000ms
- Memory
- 128MiB
- Difficulty
- (None)
- Tags
- # Submissions
- 0
- Accepted
- 0
- Uploaded By