forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Evaluate Reverse Polish Notation.cpp
61 lines (61 loc) · 1.49 KB
/
Evaluate Reverse Polish Notation.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Solution {
public:
int stoi(string s){
int n = 0;
int i = 0;
bool neg = false;
if(s[0] == '-'){
i++;
neg = true;
}
for(; i < s.size(); i++){
n = n*10 + (s[i]-'0');
}
if(neg) n = -n;
return n;
}
int evalRPN(vector<string>& tokens) {
stack<int>s;
int n = tokens.size();
for(int i = 0; i < n; i++){
string str = tokens[i];
if(str == "*"){
int n1 = s.top();
s.pop();
int n2 = s.top();
s.pop();
int res = n2*n1;
s.push(res);
}
else if(str == "+") {
int n1 = s.top();
s.pop();
int n2 = s.top();
s.pop();
int res = n2+n1;
s.push(res);
}
else if(str == "/"){
int n1 = s.top();
s.pop();
int n2 = s.top();
s.pop();
int res = n2/n1;
s.push(res);
}
else if(str == "-"){
int n1 = s.top();
s.pop();
int n2 = s.top();
s.pop();
int res = n2-n1;
s.push(res);
}
else{
int num = stoi(str);
s.push(num);
}
}
return s.top();
}
};