后缀表达式求值

原题链接:跳转点此
我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <bits/stdc++.h>
using namespace std;

int getNum(string s)
{
stack<int> exp;
int len=s.length();
int i=0;
// "12#3#+15#*"
//12#3#+15#*
//12
//15 15
//15*15
while(i<len)
{
if(s[i]=='.')
{
i++;
continue;
}
else if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'){
//加法运算
if(s[i]=='+'&&!exp.empty())
{
//出栈两个元素
int num1=exp.top();
exp.pop();
int num2=exp.top();
exp.pop();
int sum=num1+num2;
exp.push(sum);
i++;
continue;
}
//减法运算
else if(s[i]=='-'&&!exp.empty())
{
int num1=exp.top();
exp.pop();
int num2=exp.top();
exp.pop();
int dif=num2-num1;//顺序不要乱!
exp.push(dif);
i++;
continue;
}
//成发运算
else if(s[i]=='*'&&!exp.empty())
{
int num1=exp.top();
exp.pop();
int num2=exp.top();
exp.pop();
int pro=num1*num2;
exp.push(pro);
i++;
continue;
}
//除法运算
else if(s[i]=='/'&&!exp.empty())
{
int num1=exp.top();
exp.pop();
int num2=exp.top();
exp.pop();
int com=num2/num1;//这里会自动取整但是题目要求也是这样
exp.push(com);
i++;
continue;
}
}
else{
//是数字
//字符串初始值为空
string num="";
while(i<len&&s[i]>='0'&&s[i]<='9')
{
num.push_back(s[i]);
i++;
}
if(!num.empty())
{
//类型转换
int number=stoi(num);
//入栈
exp.push(number);
}
}
}
int ans=exp.top();
exp.pop();
return ans;
}

int main()
{
string s;
cin>>s;
string str="";
for(int i=0;i<s.length();i++)
{
if(s[i]!='@')
{
str+=s[i];
}
else if(s[i]=='@')
{
int ans=getNum(str);
cout<<ans<<"\n";
//清空字符串再继续遍历下一个表达式串
str="";
continue;
}
}
return 0;
//3.5.2.-*7.+@10.28.30./*7.-@
}

本题主要考察栈的应用 我这个是第一遍写的直接ac没再管 所以就代码比较复杂 其实优化一下不需要这么多行

[视频内嵌代码]