東北大學重現賽-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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章