Evaluate Reverse Polish Notation LeetCode solution in C++

1
class Solution {
2
public:
3
int stoi(string s) {
4
int n = 0;
5
int i = 0;
6
bool neg = false;
7
if (s[0] == '-') {
8
i++;
9
neg = true;
10
}
11
for (; i < s.size(); i++) {
12
n = n * 10 + (s[i] - '0');
13
}
14
if (neg) n = -n;
15
return n;
16
}
17
int evalRPN(vector<string> &tokens) {
18
stack<int> s;
19
int n = tokens.size();
20
for (int i = 0; i < n; i++) {
21
string str = tokens[i];
22
if (str == "*") {
23
int n1 = s.top();
24
s.pop();
25
int n2 = s.top();
26
s.pop();
27
int res = n2 * n1;
28
s.push(res);
29
} else if (str == "+") {
30
int n1 = s.top();
31
s.pop();
32
int n2 = s.top();
33
s.pop();
34
int res = n2 + n1;
35
s.push(res);
36
} else if (str == "/") {
37
int n1 = s.top();
38
s.pop();
39
int n2 = s.top();
40
s.pop();
41
int res = n2 / n1;
42
s.push(res);
43
} else if (str == "-") {
44
int n1 = s.top();
45
s.pop();
46
int n2 = s.top();
47
s.pop();
48
int res = n2 - n1;
49
s.push(res);
50
} else {
51
int num = stoi(str);
52
s.push(num);
53
}
54
}
55
return s.top();
56
}
57
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0