forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
40 lines (33 loc) · 1.17 KB
/
Solution.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
import java.util.Deque;
import java.util.LinkedList;
/**
* @author Oleg Cherednik
* @since 31.03.2019
*/
public class Solution {
public static void main(String... args) {
System.out.println(evaluateReversePolishNotation(new Object[] { 5, 3, '+' })); // 8
System.out.println(evaluateReversePolishNotation(new Object[] { 15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-' })); // 5
}
public static double evaluateReversePolishNotation(Object[] expr) {
Deque<Double> stack = new LinkedList<>();
for (Object item : expr) {
if (item instanceof Number)
stack.push(((Number)item).doubleValue());
else {
double two = stack.pop();
double one = stack.pop();
char op = (Character)item;
if (op == '+')
stack.push(one + two);
else if (op == '-')
stack.push(one - two);
else if (op == '/')
stack.push(one / two);
else if (op == '*')
stack.push(one * two);
}
}
return stack.pop();
}
}