东北大学重现赛-So Easy!!!(表达式求值)

Problem Description
yizhen has no girlfriend due to his stupid brain that he even can’t solve a simple arithmetic roblem. Can you help him? If you solve it and tell him the result, then he can find his lovers! So beautiful!


Input
The input consists of multiple test cases. Each test case contains some integers (every number is smaller than 2^31-1)and operator on a single line (operator including *,+,-,/ )  Process to end of file.


There are no space between number and operator and I promise that all those results of A/B is integer.


Output
For each test case, output the result of the arithmetic problem.( All those results isn’t decimal number)


Sample Input
1+2+3


1*2+2+4-5


Sample Output
6

3

题目大意:给你一个字符表达式,其中只包括 ‘+’ , ‘-’ , ‘* ’ ,‘/’ 四种运算,且保证除法运算的结果一定为整数。求表达式的值是多少?

解题思路:利用栈模拟求值.

代码:

#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
char s[1000010];
bool jude(char c)
{
	if('0'<=c&&c<='9') return true;
	else return false;
}
int main()
{
	int i,len,j,k,sum;
	stack<long long> st;
	while(scanf("%s",s)!=EOF)
	{
		while(!st.empty()) st.pop();
		len=strlen(s);
		for(i=0;i<len;)
		{
			if(jude(s[i]))
			{
				sum=0;
				while(jude(s[i]))
				{
					sum=sum*10+s[i]-'0';
					i++;
				}
				st.push(sum);
			}
			else
			{
				if(s[i]=='+')
				{
					i++;
				}
				else if(s[i]=='-')
				{
					sum=0;i++;
					while(jude(s[i]))
					{
						sum=sum*10+s[i]-'0';
						i++;
					}
					sum-=sum;
					st.push(sum);
				}
				else if(s[i]=='*')
				{
					sum=0;i++;
					while(jude(s[i]))
					{
						sum=sum*10+s[i]-'0';
						i++;
					}
					k=st.top();st.pop();
					st.push(k*sum);
				}
				else
				{
					sum=0;i++;
					while(jude(s[i]))
					{
						sum=sum*10+s[i]-'0';
						i++;
					}
					k=st.top();st.pop();
					st.push(k/sum);
				}
			}
		}
		sum=0;
		while(!st.empty())
		{
			sum+=st.top();
			st.pop();
		}
		printf("%d\n",sum);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bokzmm

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值