#include<iostream>#include<stack>#include<string>usingnamespace std;intpriority(constchar ch){switch(ch){case'+':case'-':return1;case'*':case'/':return2;default:return0;}}/**
* \brief calculate an expression
* \param a left operand
* \param b right operand
* \param ch operator
* \return result
*/intcalculate(constint a,constint b,constchar ch){switch(ch){case'+':return a + b;case'-':return a - b;case'*':return a * b;case'/':return a / b;default:return0;//never happen}}/**
* \brief judge whether a char is an operator or not
* \param ch operator
* \return is operator or not
*/boolis_operator(constchar ch){return ch =='+'|| ch =='-'|| ch =='*'|| ch =='/';}intevaluate(string expression){
stack<int> operand;//operand stack
stack<char> optr;//operator stackfor(int i =0; i < expression.length();++i){char currentCh = expression[i];if(currentCh ==' ')// neglect white space{continue;}elseif(isdigit(currentCh))//push operand stack{int num = expression[i]-'0';while(i +1< expression.length()&&isdigit(expression[i+1])){
num *=10;
num +=(expression[++i]-'0');}// cout << num;
operand.push(num);}elseif(currentCh =='(')// push '(' to stack{
optr.push('(');}elseif(currentCh ==')')// calculate expression in bracket{char cal = optr.top();
optr.pop();while(!optr.empty()&& cal !='('){int a = operand.top();
operand.pop();int b = operand.top();
operand.pop();
operand.push(calculate(b, a, cal));
cal = optr.top();
optr.pop();}}elseif(is_operator(currentCh)){// if currentChar's priority is bigger than top's, push it to stackif(optr.empty()||priority(currentCh)>priority(optr.top())){
optr.push(currentCh);}else{char cal = optr.top();
optr.pop();
optr.push(currentCh);int a = operand.top();
operand.pop();int b = operand.top();
operand.pop();
operand.push(calculate(b, a, cal));}}}while( operand.size()>1){char cal = optr.top();
optr.pop();int a = operand.top();
operand.pop();int b = operand.top();
operand.pop();
operand.push(calculate(b, a, cal));}return operand.top();}intmain(){
cout <<evaluate("6 / 3")<< endl;
cout <<evaluate("(6 / 3)")<< endl;
cout <<evaluate("2 + 2 * 3")<< endl;
cout <<evaluate("14+((13-2)*2-11*5)*2")<< endl;return0;}