Second commit

This commit is contained in:
vale 2016-05-11 18:03:29 +02:00
parent aae8344958
commit 99d10e4247

View File

@ -6,7 +6,9 @@
package com.rpn; package com.rpn;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayDeque;
import java.util.Arrays; import java.util.Arrays;
import java.util.Deque;
import java.util.List; import java.util.List;
/** /**
@ -16,6 +18,8 @@ import java.util.List;
public class ReversePolishNotation public class ReversePolishNotation
{ {
private static final String OPERATORS = "+-*/";
public static BigDecimal evalRPN(String[] params) public static BigDecimal evalRPN(String[] params)
{ {
return evalRPN(Arrays.asList(params)); return evalRPN(Arrays.asList(params));
@ -26,7 +30,42 @@ public class ReversePolishNotation
BigDecimal result = null; BigDecimal result = null;
if (null != params && !params.isEmpty()) if (null != params && !params.isEmpty())
{ {
Deque<String> stack = new ArrayDeque<>();
for (String param : params)
{
if (!OPERATORS.contains(param))
stack.push(param);
else
{
BigDecimal b = new BigDecimal(stack.pop());
BigDecimal a = new BigDecimal(stack.pop());
BigDecimal res = null;
switch (param)
{
case "+":
res = a.add(b);
break;
case "-":
res = a.subtract(b);
break;
case "*":
res = a.multiply(b);
break;
case "/":
res = a.divide(b);
break;
}
if (null != res)
stack.push(String.valueOf(res));
else
throw new IllegalStateException("Invalid operator");
}
}
result = new BigDecimal(stack.pop());
} }
return result; return result;
} }