【题解】后缀表达式的值
【题目描述】
从键盘读入一个后缀表达式(字符串),只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。每个运算数之间用一个空格隔开,不需要判断给你的表达式是否合法。以@作为结束标志。
比如,16–9*(4+3)转换成后缀表达式为:16□9□4□3□+*–,在字符数组A中的形式为:
栈中的变化情况:
运行结果:-47
提示:输入字符串长度小于250,参与运算的整数及结果之绝对值均在范围内,如有除法保证能整除。
【输入描述】
一个后缀表达式。
【输出描述】
一个后缀表达式的值。
【样例输入】
16 9 4 3 +*-@
【样例输出】
-47
【题目分析】
要计算出最终结果肯定是要后缀转中缀。然后再计算。
后缀转中缀的规则如下:
1.从左到右,遇到数就入栈,遇到操作符就出栈
2.运算规则是 栈底元素 op 栈顶元素
另外注意 字符转数字和数字转字符
【参考答案】
#include<iostream>
#include<stack>
#include<string>
using namespace std;
stack <long long> s;//因为数据最大是2的六十四次方
int main()
{
string a;
long long t = -1, m, n, ans, i = 0;
getline(cin,a);//因为有空格所以用getline,否则直接cin就可,头文件string
while (a[i] != '@')
{
if (a[i] >= '0' && a[i] <= '9')
{
if (t == -1)//最初或者当前元素是空格,直接结果压入栈
{
t = a[i] - '0';
s.push(t);
}
else//当前不是空格,之前的数字变成整数压入栈
{
t = s.top();
s.pop();
t = t * 10 + (a[i] - '0');
s.push(t);
}
}
if (a[i] == ' ')
{
t = -1;
}
if (a[i] == '+')
{
m = s.top();s.pop();n = s.top();s.pop();
ans = m + n;
s.push(ans);
}
if (a[i] == '-')
{
m = s.top(); s.pop(); n = s.top(); s.pop();
ans = n-m;
s.push(ans);
}
if (a[i] == '*')
{
m = s.top(); s.pop(); n = s.top(); s.pop();
ans = n*m;
s.push(ans);
}
if (a[i] == '/')
{
m = s.top(); s.pop(); n = s.top(); s.pop();
ans = n/ m;
s.push(ans);
}
i++;
}
cout<<s.top();
}扫描二维码推送至手机访问。
版权声明:本文由青少年编程知识记录发布,如需转载请注明出处。
