代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
题目描述
逆波兰表示法是一种将运算符(operator)写在操作数(operand)后面的描述程序(算式)的方法。举个例子,我们平常用中缀表示法描述的算式(1 + 2)*(5 + 4),改为逆波兰表示法之后则是1 2 + 5 4 + *。相较于中缀表示法,逆波兰表示法的优势在于不需要括号。
请输出以逆波兰表示法输入的算式的计算结果。
输入格式
在一行中输入1个算式。相邻的符号(操作数或运算符)用1个空格隔开。
输出格式
在一行中输出计算结果。
限制:
2≤算式中操作数的总数≤100
1≤算式中运算符的总数≤99
运算符仅包括“+”、“-”、“*”,操作数、计算过程中的值以及最终的计算结果均在int范围内。
输入样例
4 3 + 2 -
1 2 + 3 4 - *
输出样例
5
-3
个人思路
- 根据逆波兰表示法的概念可以看出要用到栈的输入输出规则。
于是便设一个字符存储中间值并碰到符号进行计算就好了- 用字符来存储中间值的想法是被运算符和输入输出案例给误导了,题目中并没有明确所有的数字都是0-9的数,所以存在多个字符存入的情况。
- 所以采用string类型来判断输入的是否为操作数,否则就识别并存入int 类型中的栈来进行运算
#include<bits/stdc++.h>
using namespace std;
int main()
{
stack<int> s;
string c;
while(cin>>c)
{
int a,b;
if(c.length()==1&&(c[0]<'0'||c[0]>'9'))
{
a=s.top();
s.pop();
b=s.top();
s.pop();
}
else
{
int temp=0;
for(int i=0;i<c.length();i++)
{
temp=temp*10+(c[i]-'0');
}
s.push(temp);
continue;
}
if(c[0]=='+')
{
s.push(a+b);
}
else if(c[0]=='-')
{
s.push(b-a);
}
else if(c[0]=='*')
{
s.push(a*b);
}
}
cout<<s.top();
}