Working code:
Code assumes that given expression will be valid and there is single digit char only to evaluate.
Code assumes that given expression will be valid and there is single digit char only to evaluate.
// Evaluating a string
bool isOperator(char op){
return ( (op=='+')||( op=='-')||(op=='*')||(op=='/'));
}
int preference(char op1,char op2){
if(op1=='(') return -1;
else if(op2=='(') return 1;
if(op1=='+' || op1=='-'){
if(op2=='+'||op2=='-')
return 0;
else
return -1;
}
else
if(op2=='+'||op2=='-')
return 1;
else
return 0;
}
int applyOperator(int first,char op,int second)
{
int f = first;
int s = second;
switch(op){
case '+':
return f+s;
break;
case '-':
return f-s;
break;
case '*':
return f*s;
break;
case '/':
return f/s;
}
}
int evaluatePostFix(string s){
stack<int> st;
for(int i=0;i<s.length();i++){
if(s[i]>='0' && s[i]<='9')
st.push(s[i]-'0');
else{
int a = st.top();
st.pop();
int b = st.top();
st.pop();
int ans = applyOperator(b,s[i],a);
//cout<<ans<<" ";
st.push(ans);
}
}
return st.top();
}
string infixToPostfixConversion(string s)
{
string postfix = ""; // Final postfix conversion of given string
stack<char> st;
for(int i=0;i<s.length();i++){
// If digit is 0 to 9 then directly print it to output
if(s[i]>='0' && s[i]<='9'){
postfix.push_back(s[i]);
}
else
if(isOperator(s[i])){
if(st.empty())
st.push(s[i]);
else
if( preference(st.top(),s[i])<0)
st.push(s[i]);
else
if(preference(st.top(),s[i])==0){
postfix.push_back(st.top());
st.pop();
st.push(s[i]);
}
else{
while(!st.empty() && preference(st.top(),s[i])>0){
//cout<<"in";
postfix.push_back(st.top());
st.pop();
}
st.push(s[i]);
}
}
else{
if(s[i]=='(')
st.push('(');
else{
//cout<<s[i]<<" "<<st.size()<<endl;
while(!st.empty() && st.top()!='('){
//cout<<st.top()<<" ";
postfix.push_back(st.top());
st.pop();
}
st.pop();
}
}
}
while(! st.empty())
{
postfix.push_back(st.top());
st.pop();
}
//cout<<postfix<<endl;
return postfix;
}
int eval(string s){
string s1 = infixToPostfixConversion(s);
cout<<"Converted String is "<<s1<<endl;
return evaluatePostFix(s1);
}
int main()
{
cout<<eval("5*(2+(3*4*5)+5/6)")<<endl;;
cout<<eval("1+2+3*(4+5)*9+4-5*2");
return 0;
}
No comments:
Post a Comment