-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00150-evaluate_reverse_polish_notation.java
More file actions
45 lines (33 loc) · 1.11 KB
/
00150-evaluate_reverse_polish_notation.java
File metadata and controls
45 lines (33 loc) · 1.11 KB
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: Evaluate Reverse Polish Notation
// https://leetcode.com/problems/evaluate-reverse-polish-notation/
import java.util.Stack;
class Solution {
// SOLUTION
public int evalRPN(String[] tokens) {
Stack<Integer> result = new Stack<>();
for (var s : tokens) {
if(s.length()>1 || Character.isDigit(s.charAt(0))) {
result.push(Integer.parseInt(s));
} else {
var x2 = result.peek(); result.pop();
var x1 = result.peek(); result.pop();
switch(s.charAt(0)) {
case '+': x1+=x2; break;
case '-': x1-=x2; break;
case '*': x1*=x2; break;
case '/': x1/=x2; break;
}
result.push(x1);
}
}
return result.peek();
}
public static void main(String[] args) {
Solution o = new Solution();
// INPUT
String[] tokens = {"2","1","+","3","*"};
// OUTPUT
var result = o.evalRPN(tokens);
System.out.println(result);
}
}