-
Notifications
You must be signed in to change notification settings - Fork 0
/
#150. Evaluate Reverse Polish Notation
53 lines (40 loc) · 1.19 KB
/
#150. Evaluate Reverse Polish Notation
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
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
Time Complexity = O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
Space Complexity = O(n)
# Code
```
/*
#150. Evaluate Reverse Polish Notation
*/
class Solution {
public:
bool checkifoper(string c) {
if(c=="+" || c=="-" || c=="*" || c=="/") return true;
else return false;
}
int evalRPN(vector<string>& tokens) {
stack <int> s;
for(int i = 0; i < tokens.size(); i++) {
if(!checkifoper(tokens[i])) s.push(stoi(tokens[i]));
else {
long int num1=s.top();
s.pop();
long int num2=s.top();
s.pop();
if(tokens[i]=="+") s.push(num1 + num2);
if(tokens[i]=="-") s.push(num2 - num1);
if(tokens[i]=="/") s.push(num2 / num1);
if(tokens[i]=="*") s.push(num2 * num1);
}
} return s.top();
}
};
```