Example #1
0
        private static CalculationResult CalculateByRPN(string input)
        {
            var result     = 0.0;
            var number     = 0.0;
            var digitStack = new Stack <double>();
            var symbols    = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            for (int i = 0; i < symbols.Length; i++)
            {
                if (double.TryParse(symbols[i], System.Globalization.NumberStyles.Float,
                                    System.Globalization.CultureInfo.InvariantCulture, out number))
                {
                    digitStack.Push(number);
                }
                else
                {
                    if (digitStack.Count() >= 2)
                    {
                        double secondArgument = digitStack.Pop();
                        if (secondArgument == 0 && symbols[i] == "/")
                        {
                            return(CalculationResult.CreateError("Division by zero"));
                        }
                        double firstArgument = digitStack.Pop();

                        switch (symbols[i])
                        {
                        case "+":
                            result = firstArgument + secondArgument;
                            break;

                        case "-":
                            result = firstArgument - secondArgument;
                            break;

                        case "*":
                            result = firstArgument * secondArgument;
                            break;

                        case "/":
                            result = firstArgument / secondArgument;
                            break;

                        case "^":
                            result = Math.Pow(firstArgument, secondArgument);
                            break;
                        }
                    }

                    else
                    {
                        return(CalculationResult.CreateError("Invalid notation"));
                    }
                    digitStack.Push(result);
                }
            }
            return(CalculationResult.CreateSuccess(digitStack.Peek()));
        }
Example #2
0
        public static CalculationResult Calculate(string input)
        {
            var validationError = ValidateInput(input);

            if (validationError != null)
            {
                return(CalculationResult.CreateError(validationError));
            }
            string rpn;
            string error;

            if (!TryGetReversePolishNotation(input, out rpn, out error))
            {
                return(CalculationResult.CreateError(error));
            }
            return(CalculateByRPN(rpn));
        }