给定一个表达式字符串,其中只包含非负整数,加法,减法以及乘法符号,例如7+3*4*5+2+4-3-1。请写程序计算该表达式的值。
提示:可以尝试使用递归算法,程序将非常简洁易写,很适用于面试场合。
还是发现自己一次把程序写对比较难啊,总是要错一些用例然后才发现错误,然后再纠正。哎
下面基本没有什么错误检测。另外注意当前操作为减的时候,下一个数转换为负是最好的,不能留着最后求值的时候再判断。
比如1-2-3,最后会得到1-(-1) =2,错误。
//返回表达式expr的值
#include<stack>
bool isOp(char c)
{
return c=='+'||c=='-'||c=='*';
}
int evaluate(const string& expr) {
if (expr.empty() )
return 0;
stack<int> operand;
operand.push(0);
stack<char> ops;
ops.push('+');
int preSum=0;
for(int i=0;i<expr.size();i++)
{
if ( expr[i]==' ')
continue;
else if ( isOp(expr[i]) )
ops.push(expr[i]);
else if (isdigit(expr[i] ))
{
preSum=preSum*10+expr[i]-'0';
if ( i==expr.size()-1||!isdigit(expr[i+1]))
{
operand.push(preSum);
preSum=0;
if ( ops.top()=='*' )
{
int a =operand.top();operand.pop();
int b =operand.top();operand.pop();
ops.pop();
operand.push(a*b);
}
else if ( ops.top()=='-' )
{
int a=operand.top();
operand.pop();
ops.top()='+';
operand.push(-a);
}
}
}
else
return -1;
}
while(!ops.empty())
{
int a =operand.top();operand.pop();
int b =operand.top();operand.pop();
int type= ops.top();
ops.pop();
int t=type=='+'?a+b:b-a;
operand.push(t);
}
return operand.top();
}