forked from gongluck/CVIP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
150.逆波兰表达式求值.cpp
50 lines (49 loc) · 1.11 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
/*
* @lc app=leetcode.cn id=150 lang=cpp
*
* [150] 逆波兰表达式求值
*/
// @lc code=start
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
std::stack<int> stack;
for (const auto &s : tokens)
{
if (s == "+" ||
s == "-" ||
s == "*" ||
s == "/")
{
auto num1 = stack.top();
stack.pop();
auto num2 = stack.top();
stack.pop();
if (s == "+")
{
stack.push(num1 + num2);
}
else if (s == "-")
{
stack.push(num2 - num1);
}
else if (s == "*")
{
stack.push(num1 * num2);
}
else if (s == "/")
{
stack.push(num2 / num1);
}
}
else
{
stack.push(std::stoi(s));
}
}
return stack.top();
}
};
// @lc code=end