-
Notifications
You must be signed in to change notification settings - Fork 0
/
Evaluate Reverse Polish Notation.cpp
75 lines (70 loc) · 2.31 KB
/
Evaluate Reverse Polish Notation.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Evaluate the value of an arithmetic expression in Reverse Polish Notation.
*
* Valid operators are +, -, *, /. Each operand may be an integer or another expression.
*
* Some examples:
* ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
* ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
*/
class Solution {
public:
int evalRPN(vector<string> &tokens) {
vector<string> stk;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "") { // error case
return INT_MAX;
}
string s1, s2;
int op1, op2;
switch (tokens[i][0]) {
case '+':
s1 = stk.back();
stk.pop_back();
s2 = stk.back();
stk.pop_back();
op1 = atoi(s1.c_str());
op2 = atoi(s2.c_str());
stk.push_back(to_string(op2 + op1));
break;
case '-':
if (tokens[i].size() > 1) { // negative number
stk.push_back(tokens[i]);
} else {
s1 = stk.back();
stk.pop_back();
s2 = stk.back();
stk.pop_back();
op1 = atoi(s1.c_str());
op2 = atoi(s2.c_str());
stk.push_back(to_string(op2 - op1));
}
break;
case '*':
s1 = stk.back();
stk.pop_back();
s2 = stk.back();
stk.pop_back();
op1 = atoi(s1.c_str());
op2 = atoi(s2.c_str());
stk.push_back(to_string(op2 * op1));
break;
case '/':
s1 = stk.back();
stk.pop_back();
s2 = stk.back();
stk.pop_back();
op1 = atoi(s1.c_str());
op2 = atoi(s2.c_str());
stk.push_back(to_string(op2 / op1));
break;
default: // assume experssions are grammatically correct
if (isdigit(tokens[i][0])) {
stk.push_back(tokens[i]);
}
break;
}
}
return atoi(stk.back().c_str());
}
};