-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00150-evaluate_reverse_polish_notation.cpp
More file actions
53 lines (38 loc) · 1.05 KB
/
00150-evaluate_reverse_polish_notation.cpp
File metadata and controls
53 lines (38 loc) · 1.05 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
// 150: Evaluate Reverse Polish Notation
// https://leetcode.com/problems/evaluate-reverse-polish-notation/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
// SOLUTION
int evalRPN(vector<string>& tokens) {
stack<int> result;
for (auto s : tokens) {
if (s.size()>1 || isdigit(s[0])) {
result.push(stoi(s));
} else {
auto x2 = result.top(); result.pop();
auto x1 = result.top(); result.pop();
switch (s[0]) {
case '+': x1+=x2; break;
case '-': x1-=x2; break;
case '*': x1*=x2; break;
case '/': x1/=x2; break;
}
result.push(x1);
}
}
return result.top();
}
};
int main() {
Solution o;
// INPUT
vector<string> tokens = {"2","1","+","3","*"};
// OUTPUT
auto result = o.evalRPN(tokens);
cout<<result<<endl;
return 0;
}