[各种面试题] 简单表达式计算

给定一个表达式字符串,其中只包含非负整数,加法,减法以及乘法符号,例如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();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值