11. 后缀表达式求值
XJOI - 题目ID:1035必做题100分
最新提交:
Runtime Error
0 分
历史最高:
Runtime Error
20 分
时间限制: 1000ms
空间限制: 65535kB
题目描述
前缀、中缀、后缀表达式是对表达式的不同记法,区别在于运算符相对于操作数的位置不同,例如两数相加。
前缀表达式的运算符位于操作数之前 → +ab
中缀表达式的运算符位于操作数中间 → a+b
后缀表达式的运算符位于操作数之后 → ab+
其中后缀表达式是一种不需要括号也可以进行正确计算的表达式。现已知后缀表达式计算值
输入格式
后缀表达式,运算符只包含 + - * / 四种,数字范围1~9。
输出格式
后缀表达式的计算值
样例
Input 1
35523*4-*1-+
Output 1
12
样例解释
先计算23∗23∗ ->2∗32∗3,结果为6。
算式变成3564−∗1−+3564−∗1−+,再计算64−64−->6−46−4,结果为2
算式变成352∗1−+352∗1−+,再计算52∗52∗->5∗25∗2,结果为10
算式变成3(10)1−+3(10)1−+,再计算(10)1−(10)1−->10−110−1,结果为9
算式变成39+39+,最后计算39+39±>3+93+9,最终结果为12。
样例对应的式子实际上就是:3+(5*(3*2-4)-1),计算顺序不由大小关系决定,而由操作符顺序决定。
数据范围
所有数字范围0~9。
代码:
#include<iostream>
#include<cstring>
using namespace std;
int stack[260];
int top=0;
int main()
{
char a[260];
cin.getline(a,260);
int i=0,x=0,t1,t2;
while(a[i]!='#')
{
if(a[i]>='0' && a[i]<='9') {
x=0;
while(a[i]>='0' && a[i]<='9')
{
x=x*10+a[i]-'0';
i++;
}
stack[++top]=x;
}
if(a[i]=='+')
{
t1=stack[top--];
t2=stack[top--];
stack[++top]=t1+t2;
}
else if(a[i]=='*')
{
t1=stack[top--];
t2=stack[top--];
stack[++top]=t1*t2;
}
else if(a[i]=='-')
{
t2=stack[top--];
t1=stack[top--];
stack[++top]=t1-t2;
}
else if(a[i]=='/')
{
t2=stack[top--];
t1=stack[top--];
stack[++top]=t1/t2;
}
i++;
}
cout<<stack[top];
return 0;
}