forked from coder2hacker/Explore-open-source
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEvalutatePostFix.java
45 lines (38 loc) · 1.54 KB
/
EvalutatePostFix.java
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
//Input: tokens = ["2","1","+","3","*"]
//Output: 9
//Explanation: ((2 + 1) * 3) = 9
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for(String s : tokens){
if(Objects.equals(s, "+") || Objects.equals(s, "-") || Objects.equals(s, "/") || Objects.equals(s, "*")){
if(s.equals("+")){
int first = Integer.parseInt(stack.pop());
int second = Integer.parseInt(stack.pop());
int n = second+first;
stack.push(Integer.toString(n));
}
else if(s.equals("-")){
int first = Integer.parseInt(stack.pop());
int second = Integer.parseInt(stack.pop());
int n = second-first;
stack.push(Integer.toString(n));
}
else if(s.equals("*")){
int first = Integer.parseInt(stack.pop());
int second = Integer.parseInt(stack.pop());
int n = second*first;
stack.push(Integer.toString(n));
}
else if(s.equals("/")){
int first = Integer.parseInt(stack.pop());
int second = Integer.parseInt(stack.pop());
int n = second/first;
stack.push(Integer.toString(n));
}
}
else{
stack.push(s);
}
}
return Integer.parseInt(stack.pop());
}