逆波兰表示法是一种将运算符(operator)写在操作数(operand)后面的描述程序(算式)的方法。举个例子,我们平常用中缀表示法描述的算式(1 + 2)*(5 + 4),改为逆波兰表示法之后则是1 2 + 5 4 + *。相较于中缀表示法,逆波兰表示法的优势在于不需要括号。
请输出以逆波兰表示法输入的算式的计算结果。
输入格式:
在一行中输入1个算式。相邻的符号(操作数或运算符)用1个空格隔开。
输出格式:
在一行中输出计算结果。
限制:
2≤算式中操作数的总数≤100
1≤算式中运算符的总数≤99
运算符仅包括“+”、“-”、“*”,操作数、计算过程中的值以及最终的计算结果均在int范围内。
输入样例1:
4 3 + 2 -
输出样例1:
5
输入样例2:
1 2 + 3 4 - *
输出样例2:
-3
思路:咳咳就不说我为啥没拿满分了,我自己至今不明白当时自己的脑回路是什么。
这道题就是遇到符号就弹出两个数,特别注意的是小数问题,再就是不输出多余的0。
下面给出AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int maxn=500+10;
stack<double> s;
string str;
int main()
{
getline(cin,str);
for(int i=0; i<str.size(); i++)
{
if(str[i]==' ') continue;
else if(str[i]=='+')
{
double t=s.top();
s.pop();
double tt=s.top();
s.pop();
s.push(t+tt);
}
else if(str[i]=='*')
{
double t=s.top();
s.pop();
double tt=s.top();
s.pop();
s.push(t*tt);
}
else if(str[i]=='-')
{
double t=s.top();
s.pop();
double tt=s.top();
s.pop();
s.push(tt-t);
}
else
{
double ans=0,ans1=0;
int j;
for(j=i;j<str.size();j++)
{
if(str[j]=='.'||str[j]==' ') break;
ans=ans*10+str[j]-'0';
}
if(str[j]=='.')
{
double t=0.1;
for(j=j+1; j<str.size(); j++)
{
if(str[j]==' ') break;
ans1+=(str[j]-'0')*t;
t*=0.1;
}
}
//cout<<"G "<<ans<<" "<<ans1<<endl;
i=j;
s.push(ans+ans1);
}
}
printf("%g",s.top());
return 0;
}