-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluateReversePolishNotation.cpp
More file actions
35 lines (33 loc) · 980 Bytes
/
EvaluateReversePolishNotation.cpp
File metadata and controls
35 lines (33 loc) · 980 Bytes
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
#include <iostream>
#include <vector>
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for (auto it: tokens) {
if (it == "*" || it == "-" || it == "+" || it == "/") {
int operand1 = s.top();
s.pop();
int operand2 = s.top();
s.pop();
if (it == "*") s.push(operand2 * operand1);
else if (it == "-") s.push(operand2 - operand1);
else if (it == "+") s.push(operand2 + operand1);
else if (it == "/") s.push(operand2 / operand1);
}
else {
s.push(stoi(it));
}
}
return s.top();
}
};
int main() {
vector<string> tokens = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
Solution sol;
cout << sol.evalRPN(tokens) << endl;
return 0;
}