后缀表达式
题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
如:$\texttt{3*(5-2)+7}$ 对应的后缀表达式为:$\texttt{3.5.2.-*7.+@}$。在该式中,@
为表达式的结束符号。.
为操作数的结束符号。
输入格式
输入一行一个字符串 $s$,表示后缀表达式。
输出格式
输出一个整数,表示表达式的值。
样例 #1
样例输入 #1
3.5.2.-*7.+@
样例输出 #1
16
提示
数据保证,$1 \leq |s| \leq 50$,答案和计算过程中的每一个值的绝对值不超过 $10^9$。
简单栈就可以解决
CODE(C++)
#include<iostream>
using namespace std;
int main()
{
char t;
stack<int> s;
int num =0 ;
while(cin>>t&&t!='@')
{
if(t == '.') {
s.push(num);
num = 0;
}
if(t >= '0' && t <= '9') {
num = num * 10 + t - '0';
}
if(t=='+')
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b+a);
}
if(t=='-')
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b-a);
}
if(t=='/')
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b/a);
}
if(t=='*')
{
int a=s.top();
s.pop();
int b=s.top();
s.pop();
s.push(b*a);
}
}
cout<<s.top()<<endl;
return 0;
}
markdown…
?