3993 - 栈实现表达式求值

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 128 MB

算数四则运算的规则是1.先乘除,后加减;2.从左算到右;3.先括号内,后括号外。

由此,算式4+2*3-10/5的计算顺序为4+2*3-10/5=4+6-10/5=4+6-2=8。

给定一个以阿拉伯数字或"("开始,以"#"结尾的整数表达式。求表达式的结果。

表达式中只包含以下字符:()+-*/0123456789

参与运算的整数和运算结果的整数,都不超过20亿

题目输入

输入为若干行,每个表达式占一行


题目输出

输出一个整数,表示表达式的运算结果

输入/输出样例

输入格式

4+2*3-10/5#
33*(11-2)#
2*3/2#

输出格式

8
297
3

C++解答

#include <iostream>
#include <stack>
using namespace std;
string fun1(string s)//中缀转后缀 
{
	stack<char> a;
	string r="";
	for(int i=0;i<s.length()-1;i++)
	{
		 if(s[i]>='0'&&s[i]<='9')
		 {
		 	r+=s[i];
		 	if(s[i+1]=='#'||!(s[i+1]>='0'&&s[i+1]<='9'))//下一个字符不是数字
		 	{
		 		r+=" ";
		 	}
		 }
		 else//非数字 
		 {
			if(s[i]==')')
			{
				while(a.top()!='(')
				{
					r=r+a.top()+" "; 
					a.pop();
				}
				a.pop();//左括号出栈 
			}
			else
			{
				while(!a.empty()&&s[i]!='('&&a.top()!='('&&!(s[i]=='*'&&a.top()=='+')&&!(s[i]=='*'&&a.top()=='-')&&!(s[i]=='/'&&a.top()=='+')&&!(s[i]=='/'&&a.top()=='-'))
		 		{
		 			if(a.top()!='(')
		 			{
		 				r=r+a.top()+" ";
		 			}
					a.pop();
		 		}
				a.push(s[i]);
			}
		 }
	}
	while(!a.empty())
	{
		r=r+a.top()+" ";
		a.pop();
	}
	return r;
}
int fun2(string s)//后缀表达式求值 
{
	stack<int> a;
	int x,y,z=0;
	for(int i=0;i<s.length();i++)
	{
		if(s[i]>='0'&&s[i]<='9')
		{
			z=z*10+s[i]-'0';
			if(i==s.length()-1 || s[i+1]==' ')//下一个字符不是数字 
			{
				a.push(z);
				z=0;
			}	
		}
		else if(s[i]!=' ')
		{
			x=a.top();
			a.pop();
			y=a.top();
			a.pop();
			if(s[i]=='*')
			{
				a.push(y*x);	
			}
			else if(s[i]=='/')
			{
				a.push(y/x);	
			}
			else if(s[i]=='+')
			{
				a.push(y+x);	
			}
			else
			{
				a.push(y-x);	
			}
		}
	}
	return a.top();
}
int main()
{
	string s;
	while(cin>>s)
	{
		string t = fun1(s);
		cout<<fun2(t)<<endl;
	}
	return 0;
}