-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy path150.逆波兰表达式求值.cpp
58 lines (55 loc) · 1.24 KB
/
150.逆波兰表达式求值.cpp
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
/*
* @lc app=leetcode.cn id=150 lang=cpp
*
* [150] 逆波兰表达式求值
*/
// @lc code=start
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
std::stack<int> st;
for (const auto &s : tokens)
{
if (s == "+")
{
auto n2 = st.top();
st.pop();
auto n1 = st.top();
st.pop();
st.push(n1 + n2);
}
else if (s == "-")
{
auto n2 = st.top();
st.pop();
auto n1 = st.top();
st.pop();
st.push(n1 - n2);
}
else if (s == "*")
{
auto n2 = st.top();
st.pop();
auto n1 = st.top();
st.pop();
st.push(n1 * n2);
}
else if (s == "/")
{
auto n2 = st.top();
st.pop();
auto n1 = st.top();
st.pop();
st.push(n1 / n2);
}
else
{
st.push(std::atoi(s.c_str()));
}
}
return st.top();
}
};
// @lc code=end