-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_STOII_0036_evalRPN.cc
52 lines (49 loc) · 1.1 KB
/
Problem_STOII_0036_evalRPN.cc
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
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// seem as leetcode 0150
// https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
// see at Problem_0150_evalRPN.cc
class Solution
{
public:
bool isNumber(string &token) { return token != "+" && token != "-" && token != "*" && token != "/"; }
int evalRPN(vector<string> &tokens)
{
vector<int> stack;
int n = tokens.size();
for (int i = 0; i < n; i++)
{
string &token = tokens[i];
if (isNumber(token))
{
stack.push_back(stoi(token));
}
else
{
int num2 = stack.back();
stack.pop_back();
int num1 = stack.back();
stack.pop_back();
switch (token[0])
{
case '+':
stack.push_back(num1 + num2);
break;
case '-':
stack.push_back(num1 - num2);
break;
case '*':
stack.push_back(num1 * num2);
break;
case '/':
stack.push_back(num1 / num2);
break;
}
}
}
return stack.back();
}
};