题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
如:3*(5–2)+7对应的后缀表达式为:3.5.2.-*7.+@。’@’为表达式的结束符号。‘.’为操作数的结束符号。
输入格式
输入:后缀表达式
输出格式
输出:表达式的值
输入输出样例
输入
3.5.2.-*7.+@
输出
16
说明/提示
字符串长度,1000内。
解题思路:
将每个操作数入栈,遇到操作符时则将最顶上的两个操作数弹出进行计算,然后将计算后的数压入栈中,作为下一个操作数;最后留在栈中的就是最后的结果。
可能这题的难点在于,如何获取数字,因为题目会使用.
作为数字的结束符,所以在每次输入的时候就用一个数累加,如num = num * 10 + (ch - '0');
这样就可以获取到数字。
AC代码如下:
#include<iostream>
#include<stack>
using namespace std;
int main(){
// 存放取出来的操作数
long long op1, op2;
char ch;
stack<long long> sta;
// 存放输入的数字
long long num = 0;
while (cin >> ch, ch != '@'){
switch (ch)
{
case '+':{
//获取操作数
op1 = sta.top(); sta.pop();
op2 = sta.top(); sta.pop();
// 要后取的操作数放前面
sta.push(op2 + op1); break;
}
case '-':{
op1 = sta.top(); sta.pop();
op2 = sta.top(); sta.pop();
sta.push(op2 - op1); break;
}
case '*':{
op1 = sta.top(); sta.pop();
op2 = sta.top(); sta.pop();
sta.push(op2 * op1); break;
}
case '/':{
op1 = sta.top(); sta.pop();
op2 = sta.top(); sta.pop();
sta.push(op2 / op1); break;
}
case '.':{
sta.push(num); num = 0; break;
}
default: {
num = num * 10 + (ch - '0'); break;
}
}
}
cout << sta.top() << endl;
return 0;
}