PTA 逆波兰表达式求值
题目描述:
逆波兰表示法是一种将运算符(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
思路:
代码:
#include<iostream>
#include<cstdio>
#include<stack>
#include<string>
using namespace std;
stack<int>sta;
string str;
int main(){
int i = 0;
getline(cin,str);
int str_count = str.length();
int pri_count = 0;
int flag = 0;
while(pri_count < str_count){
char x1 = str[ pri_count++ ];
//如果是数字
int a;
if( x1>='0' && x1<='9' ){
char x2 = str[pri_count++];
int m = 10;
a = x1-'0';
if( x2>='0' && x2<='9' ){
while( x2>='0' && x2<='9' ){
a = a * 10 + ( x2 - '0');
x2 = str[ pri_count++ ];
}
}
if(flag) a = a *(-1);
flag = 0;
sta.push(a);
}
else if(x1 == ' '){
continue;
}
else if(x1 == '-'){
if(str[pri_count]>='0' && str[pri_count<='9'){
flag = 1;
continue;
}
else{
int n1 = sta.top();
sta.pop();
int n2 = sta.top();
sta.pop();
int n3 = n2 - n1;
sta.push(n3);
}
}
else{
int n1 = sta.top();
sta.pop();
int n2 = sta.top();
sta.pop();
int n3;
switch(x1){
case '+': n3 = n1 + n2; break;
case '*': n3 = n1 * n2; break;
case '/': n3 = n2 / n1; break;
}
sta.push(n3);
}
}
printf("%d",sta.top());
return 0;
}