public string Parse(string task) { string[] taskInLines = Regex.Split(PrepareTask(task).Replace(" ", ""), "(?<=[-+*/()^])|(?=[-+*/()^])").Where(i => i != "").ToArray(); foreach (var taskLine in taskInLines) { if (IsNegative(taskLine)) { _isCurrentNegative = true; continue; } if (!CalculatorUtilities.IsOperatorOrBracket(taskLine)) { _convertedTask += (IsNegativeNumber(taskLine) ? "-" : "") + (taskLine + " "); _isCurrentNegative = false; } else { OperationsPriorityHandler(taskLine); } _taskLineBefore = taskLine; } if (_operationsBuffer.Count > 0) { OperationsPriorityHandler(isLast: true); } return(_convertedTask); }
public double Calculate(string rpnTask) { if (string.IsNullOrEmpty(rpnTask)) { return(0); } var task = new List <string>(rpnTask.Split(' ')); var taskBuffer = new Stack <double>(); foreach (var taskLine in task) { if (!string.IsNullOrEmpty(taskLine)) { taskBuffer.Push( !CalculatorUtilities.IsOperatorOrBracket(taskLine) ? double.Parse(taskLine) : CalculatorUtilities.Compute(taskLine, taskBuffer.Pop(), taskBuffer.Pop()) ); } } return(taskBuffer.Count <= 1 ? taskBuffer.Pop() : taskBuffer.Sum()); }
private bool IsNegativeNumber(string currentLine) { return(_isCurrentNegative && !CalculatorUtilities.IsOperatorOrBracket(currentLine)); }