-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0150-evaluate-reverse-polish-notation.cpp
More file actions
43 lines (35 loc) · 1 KB
/
0150-evaluate-reverse-polish-notation.cpp
File metadata and controls
43 lines (35 loc) · 1 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
/*
Evaluate RPN, valid operators: +, -, *, /
Stack, if num push, if operator apply to top 2 nums
Time: O(n)
Space: O(n)
*/
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for (int i = 0; i < tokens.size(); i++) {
string token = tokens[i];
if (token.size() > 1 || isdigit(token[0])) {
stk.push(stoi(token));
continue;
}
int num2 = stk.top();
stk.pop();
int num1 = stk.top();
stk.pop();
int result = 0;
if (token == "+") {
result = num1 + num2;
} else if (token == "-") {
result = num1 - num2;
} else if (token == "*") {
result = num1 * num2;
} else {
result = num1 / num2;
}
stk.push(result);
}
return stk.top();
}
};