1331:【例1-2】后缀表达式的值时间限制: 10 ms 内存限制: 65536 KB 提交数: 22710 通过数: 4230 【题目描述】读入一个后缀表达式(字符串),只含有0-9组成的运算数及加(+)、减(—)、乘(*)、除(/)四种运算符。每个运算数之间用一个空格隔开,不需要判断给你的表达式是否合法。以@作为结束标志。 比如,16–9*(4+3)转换成后缀表达式为:16□9□4□3□+*–,在字符数组A中的形式为: 栈中的变化情况: 运行结果:-47 提示:输入字符串长度小于250,参与运算的整数及结果之绝对值均在264264范围内,如有除法保证能整除。 【输入】一个后缀表达式。 【输出】一个后缀表达式的值。 【输入样例】 【输出样例】 |
教学备忘录:编辑 |
无 |
给学生提示:编辑 |
无 |
遇到数字就保存到num数组中(可能是多位数,需进行处理),注意数据范围,num数组需用longlong,否则过不了。
遇到字符就让最后保存的两个数进行运算,注意减法和除法的运算顺序,倒数第二个保存的数减去(除以)最后保存的那个数,运算后将结果保存在倒数第二个保存的数的位置(此时这个数更新为最后保存的数的位置,其数组下标前一个位置则为此时的倒数第二个保存的数),以此类推,这是用数组模拟栈的方法。
#include <iostream>
#include <string>
#include <stack>
#include <cstring>
using namespace std;
long long num[1005];
int main()
{
string str;
getline(cin, str);
int len = str.length();
int cnt = 0;
for (int i = 0; i < len - 1; i ++) { // i<len-1为了不包含最后的@
if (str[i] == '+') { // 对四则运算进行处理 注意减法和除法的 被减数 和 被除数 的位置
num[cnt-2] += num[cnt-1];
cnt --;
}
else if (str[i] == '-') {
num[cnt-2] -= num[cnt-1];
cnt --;
}
else if (str[i] == '*') {
num[cnt-2] *= num[cnt-1];
cnt --;
}
else if (str[i] == '/') {
num[cnt-2] /= num[cnt-1];
cnt --;
}
else {
long long x = 0;
while (str[i] != ' ') {
x = x*10 + str[i]-'0';
i ++;
}
num[cnt++] = x;//printf("%lld\n", x); //测试num中保存的数值
}
}
cout << num[0] << endl;
return 0;
}
补充一个用stack的
#include <iostream>
#include <string>
#include <cstdio>
#include <stack>
#include <cstring>
using namespace std;
stack <long long> s;
int main()
{
string str;
getline(cin, str);
int len = str.length();
long long x;
for (int i = 0; i < len - 1; i ++) {
x = 0;
long long a, b;
if (str[i] == '+') {
a = s.top();
s.pop();
b = s.top();
s.pop();
s.push(a+b);
}
else if (str[i] == '-') {
a = s.top();
s.pop();
b = s.top();
s.pop();
s.push(b-a);
}
else if (str[i] == '*') {
a = s.top();
s.pop();
b = s.top();
s.pop();
s.push(a*b);
}
else if (str[i] == '/') {
a = s.top();
s.pop();
b = s.top();
s.pop();
s.push(b/a);
}
while (str[i] >= '0' && str[i] <= '9') {
x = x*10 + str[i]-'0';
if (str[i+1] == ' ') {
s.push(x);
x = 0;
}
i ++;
}
}
printf("%lld\n", s.top());
return 0;
}