-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0150-evaluate-reverse-polish-notation.cpp
45 lines (42 loc) · 1.19 KB
/
0150-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
/*
150. Evalute Reverse Polish Notation
Submitted: November 16, 2024
Runtime: 0 ms (beats 100.00%)
Memory: 15.74 MB (beats 61.18%)
*/
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stack;
for (const string& token : tokens) {
if (token == "+") {
int x = stack.top();
stack.pop();
int y = stack.top();
stack.pop();
stack.push(x + y);
} else if (token == "-") {
int y = stack.top();
stack.pop();
int x = stack.top();
stack.pop();
stack.push(x - y);
} else if (token == "*") {
int x = stack.top();
stack.pop();
int y = stack.top();
stack.pop();
stack.push(x * y);
} else if (token == "/") {
int y = stack.top();
stack.pop();
int x = stack.top();
stack.pop();
stack.push(x / y);
} else {
stack.push(stoi(token));
}
}
return stack.top();
}
};