/// <summary> /// /// </summary> /// <param name="inputString">string in infix notation</param> /// <returns></returns> public string ReversePolishNotation(string inputString) { var output = string.Empty; var stack = new Stack <char>(); for (int i = 0; i < inputString.Length; i++) { if (ExpressionProcessor.IsDelimeter(inputString[i])) { continue; } if (ExpressionProcessor.IsPartOfDecimalNumber(inputString[i])) { var value = ExpressionProcessor.GetFirstOccurrenceOfOperand(inputString, i); output += value + " "; i += value.Length - 1; } else if (ExpressionProcessor.IsOperator(inputString[i])) { ProcessOperator(inputString[i], stack, ref output); } else { throw new ArgumentException($"Unknown character {inputString[i]} in expression"); } } if (stack.Contains('(')) { throw new ArgumentException("Closing parenthesis is missing in expression"); } while (stack.Count != 0) { output += stack.Pop() + " "; } return(output); }
/// <summary> /// /// </summary> /// <param name="inputString"></param> /// <returns>String in reverse polish notation</returns> public double CalculateFromReversePolishNotation(string inputString) { var stack = new Stack <double>(); for (int i = 0; i < inputString.Length; i++) { if (ExpressionProcessor.IsDelimeter(inputString[i])) { continue; } if (ExpressionProcessor.IsPartOfDecimalNumber(inputString[i])) { var value = ExpressionProcessor.GetFirstOccurrenceOfOperand(inputString, i); stack.Push(double.Parse(value)); i += value.Length - 1; } else if (ExpressionProcessor.IsOperator(inputString[i])) { double operand1; double operand2; if (stack.Count < 2) { throw new ArgumentException("Something wrong with operators and operands"); } operand2 = stack.Pop(); operand1 = stack.Pop(); var result = Calculate(operand1, operand2, inputString[i]); stack.Push(result); } } return(stack.Peek()); }