From 99d10e4247b8dbd5c81533855d17fc6ecede29b8 Mon Sep 17 00:00:00 2001 From: vale Date: Wed, 11 May 2016 18:03:29 +0200 Subject: [PATCH] Second commit --- .../src/com/rpn/ReversePolishNotation.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/ReversePolishNotation/src/com/rpn/ReversePolishNotation.java b/ReversePolishNotation/src/com/rpn/ReversePolishNotation.java index 2a60721..84081e2 100644 --- a/ReversePolishNotation/src/com/rpn/ReversePolishNotation.java +++ b/ReversePolishNotation/src/com/rpn/ReversePolishNotation.java @@ -6,7 +6,9 @@ package com.rpn; import java.math.BigDecimal; +import java.util.ArrayDeque; import java.util.Arrays; +import java.util.Deque; import java.util.List; /** @@ -16,6 +18,8 @@ import java.util.List; public class ReversePolishNotation { + private static final String OPERATORS = "+-*/"; + public static BigDecimal evalRPN(String[] params) { return evalRPN(Arrays.asList(params)); @@ -26,7 +30,42 @@ public class ReversePolishNotation BigDecimal result = null; if (null != params && !params.isEmpty()) { + Deque 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; }