-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathevaluate_reverse_polish_notation.cpp
More file actions
53 lines (44 loc) · 1014 Bytes
/
evaluate_reverse_polish_notation.cpp
File metadata and controls
53 lines (44 loc) · 1014 Bytes
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
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> results;
for (int i = 0; i < tokens.size(); ++i) {
string token = tokens[i];
if (is_operator(token)) {
int val_1;
int val_2;
val_2 = results.top();
results.pop();
val_1 = results.top();
results.pop();
results.push(do_op(val_1, val_2, token));
}
else {
results.push(atoi(token.c_str()));
}
}
return results.top();
}
protected:
bool is_operator(string &token) {
char op = token[0];
return (1 == token.length()) &&
(('+' == op) ||
('-' == op) ||
('*' == op) ||
('/' == op));
}
int do_op(int val_1, int val_2, string &token) {
char op = token[0];
switch(op) {
case '+':
return val_1 + val_2;
case '-':
return val_1 - val_2;
case '*':
return val_1 * val_2;
default: // '/'
return val_1 / val_2;
}
}
};