#Title Description#
Xiao Ming wants to break a password door.There is an arithmetic on the door, where only'(')',')','0-9','+','-','*','/','^', the value is the password.Xiao Ming is not good at maths. He needs your help.("/" divided by integers)
#Input Format#
An expression with only one line (length <=30).
#Output Format#
The value of the output formula (all data are in the range 2^31-1).
#Sample Data#
input
1+(3+2)*(7^2+6*9)/(2)
output
258
#Analysis#
This question only needs two stacks:
1) Record all symbols
2) Record all numbers
Numbers are treated just like subtracting the ACSCLL code (note: not necessarily a single digit), but the symbols are sequential.So we have to confirm the precedence of this symbol each time we put it in. If the precedence is lower than the precedence of the previous symbol, we will finish the previous operation before putting this symbol on the stack.Otherwise put it directly (if its previous character is'(', special judgment exits).
#Code#
#include<bits/stdc++.h> using namespace std; string s; char sym[100100]={};//Create a character stack int num[100100]={};//Create a Number Stack int head1;//Top of Character Stack int head2;//Top of Number Stack int check(char a) { if(a=='+'||a=='-') return 1;//First operation if(a=='*'||a=='/') return 2;//Second operation if(a=='^') return 3;//Third operation } void cumpute() { head2--; if(sym[head1]=='+') num[head2]+=num[head2+1]; if(sym[head1]=='-') num[head2]-=num[head2+1]; if(sym[head1]=='*') num[head2]*=num[head2+1]; if(sym[head1]=='/') num[head2]/=num[head2+1]; if(sym[head1]=='^') num[head2]=pow(num[head2],num[head2+1]); head1--;//Stack Top Symbol Out }//Corresponding operations int main() { cin>>s; int i=0; sym[0]='('; s+=')'; for(;i<=s.size()-1;) { int f=0; long long x=0; for(;s[i]<='9'&&s[i]>='0';) { x=x*10+s[i]-'0'; i++; f=1; } if(f==1) num[++head2]=x;//Put numbers in if(s[i]=='(') sym[++head1]=s[i++];//If it is'('put directly if(s[i]==')') { for(;sym[head1]!='(';) cumpute();//Calculation i++; head1--; } if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||s[i]=='^') { for(;check(s[i])<=check(sym[head1])&&sym[head1]!='(';) cumpute();//Determine priority, if lower than the previous one, calculate first sym[++head1]=s[i++];//Stack Symbols } } for(;head1>=1;) cumpute();//If there are symbols in the stack, continue the calculation cout<<num[1]<<endl; return 0; }