forked from iostalks/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluateReversePolishNotation.cpp
40 lines (40 loc) · 1.22 KB
/
evaluateReversePolishNotation.cpp
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
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> myStack;
for(auto str : tokens) {
if(str != "+" && str != "-" && str != "*" && str != "/") {
myStack.push(stoi(str));
}
else {
int second = myStack.top(); myStack.pop();
int first = myStack.top(); myStack.pop();
int result;
switch (str[0]) {
case '+':{
result = first + second;
break;
}
case '-':{
result = first - second;
break;
}
case '*':{
result = first * second;
break;
}
case '/':{
result = first / second;
break;
}
default:{
result = 0;
break;
}
}
myStack.push(result);
}
}
return myStack.size() == 1 ? myStack.top() : 0;
}
};