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
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;
}