Description
对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。
Input
输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。
Output
求该后缀式所对应的算术表达式的值,并输出之。
Sample
Input
59*684/-3*+#
Output
57
Hint
基本操作数都是一位正整数!
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;
int top=0,Stack[1001];
char Str[1001];
int cal(int a,int b,char c)//运算函数
{
int y;
if(c=='+')
{
y=b+a;
}
else if(c=='-')
{
y=b-a;
}
else if(c=='*')
{
y=b*a;
}
else if(c=='/')
{
y=b/a;
}
return y;
}
int main()
{
cin>>Str;
for(int i=0; Str[i]!='#'; i++)
{
int result;
if(Str[i]>='1'&&Str[i]<='9')
{
Stack[++top]=Str[i]-'0';//化整入栈
}
else
{
result=cal(Stack[top],Stack[top-1],Str[i]);
top--;//存到下一位
Stack[top]=result;
}
}
printf("%d\n",Stack[top]);
return 0;
}