时间限制:1000MS 代码长度限制:10KB
提交次数:0 通过次数:0
题型: 编程题 语言: G++;GCC
Description
人最熟悉的是中缀表达式,但计算机比较难处理中缀表达式,所以往往将中缀表达式改为后缀表达式。
后缀表达式,又称逆波兰式。现在从键盘读入一个后缀表达式,只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。
每个运算数之间用一个空格隔开,题目所使用的运算数均小于10,并确保所给的表达式合法。以@作为结束标志。
输入格式
一个后缀表达式。
输出格式
表达式结果。
输入样例
6 9 4 3 +*-@
输出样例
-57
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<stack>
#include<cstring>
using namespace std;
int main()
{
stack<int> c;
char b[1000];
gets(b);
c.push((int)b[0] - 48);
for (int i = 0; b[i] != '@'; i++)
{
if (((int)b[i] - 48) >= 0 && ((int)b[i] - 48) <= 9)
c.push((int)b[i] - 48);
else if (b[i] != ' ')
{
int m = c.top();
c.pop();
int n = c.top();
c.pop();
if (b[i] == '+')
c.push(n + m);
else if (b[i] == '-')
c.push(n - m);
else if (b[i] == '*')
c.push(n * m);
else if (b[i] == '/')
c.push(n / m);
}
}
int x = c.top();
cout << x;
}