-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path150-evaluate-reverse-polish-notation.cpp
More file actions
47 lines (37 loc) · 1.39 KB
/
Copy path150-evaluate-reverse-polish-notation.cpp
File metadata and controls
47 lines (37 loc) · 1.39 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
class Solution {
public:
int evalRPN(vector<string>& tokens) {
function<int(string)> toInt = [](string s) -> int {
int res = 0;
for(auto c: s) {
if (c == '-') continue;
res = res * 10; res += (c - '0');
}
return s[0] == '-' ? -res: res;
};
stack<int> args;
unordered_set<char> operations = {'+', '-', '*', '/'};
for(auto token: tokens) {
if (token.size() == 1 && operations.count(token[0])) {
auto secondArg = args.top(); args.pop();
auto firstArg = args.top(); args.pop();
int res = 0;
switch (token[0]) {
case '+':
res = firstArg + secondArg;
break;
case '-':
res = firstArg - secondArg;
break;
case '*':
res = firstArg * secondArg;
break;
case '/':
res = firstArg / secondArg;
}
args.push(res);
} else args.push(toInt(token));
}
return args.top();
}
};