-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0150_Evaluate-Reverse-Polish-Notation.cpp
More file actions
92 lines (90 loc) · 2.61 KB
/
0150_Evaluate-Reverse-Polish-Notation.cpp
File metadata and controls
92 lines (90 loc) · 2.61 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// recursive method
class Solution {
public:
int idx;
bool is_operator(string &s) {
return s == "*" || s == "+" || s == "-" || s == "/";
}
int evalRPN(vector<string> &tokens) {
idx = tokens.size() - 1;
return eval(tokens);
}
int eval(vector<string> &tokens) {
if (idx < 0)
return 0;
if (is_operator(tokens[idx])) {
if (tokens[idx] == "+") {
idx--;
int l = eval(tokens);
idx--;
int r = eval(tokens);
return l + r;
} else if (tokens[idx] == "-") {
idx--;
int l = eval(tokens);
idx--;
int r = eval(tokens);
return r - l;
} else if (tokens[idx] == "*") {
idx--;
long long int l = eval(tokens);
idx--;
long long int r = eval(tokens);
return l * r;
} else {
// divide
idx--;
int l = eval(tokens);
idx--;
int r = eval(tokens);
return ((double) r / (double) l);
}
} else {
return stoi(tokens[idx]);
}
return 0;
}
};
// stack method
class Solution {
public:
bool is_operator(string &s) {
return s == "*" || s == "+" || s == "-" || s == "/";
}
int evalRPN(vector<string> &tokens) {
stack<long long> st;
for (auto &s : tokens) {
if (!is_operator(s)) {
st.emplace(stoi(s));
} else {
if (s == "+") {
long long r = st.top();
st.pop();
long long l = st.top();
st.pop();
st.emplace(l + r);
} else if (s == "-") {
long long r = st.top();
st.pop();
long long l = st.top();
st.pop();
st.emplace(l - r);
} else if (s == "*") {
long long r = st.top();
st.pop();
long long l = st.top();
st.pop();
st.emplace(l * r);
} else {
// divide
long long r = st.top();
st.pop();
long long l = st.top();
st.pop();
st.emplace((double) l / (double) r);
}
}
}
return st.top();
}
};