Coding Challenge – Reverse Polish Calculator

 Reverse polish notation is a system in which the operators follow the operands.  For example 2 3 + would mean that 2 and 3 should be summed together. It does not need any parenthesis as long as the operators work on a fixed number of operands.

Anyways, the coding challenge today is to create a reverse polish notation calculator that takes its arguments from the standard input.

So, to start out let’s go over some examples.  The solution to each example will be posted in bold while the problem will be in regular text. The following are the examples:

  1. 3 3 + = 6
  2. 3 3 2 + – = 2

Here are the explanations of the above examples:

  1. This evaluates as 3 + 3
  2. This example 3 + 2 = 5 then 3 – 5 = -2

OK, I hope that was enough information for you to process things.  Now, go ahead and try to program a calculator.  Hint: Use a stack!

View solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace Pessetto
{
    public class ReversePolishCalculator
    {
        public static void Main(string[] args)
        {
            string[] arguments = (new string[]{"0","0"}).Concat(Console.ReadLine().Split(' ')).ToArray();
            Stack<double> operandStack = new Stack<double>();
            foreach(string arg in arguments)
            {
                double number;
                double right = 0, left = 0;
                if(Double.TryParse(arg,out number))
                {
                    operandStack.Push(number);
                }
                else
                {
                    right = operandStack.Pop();
                    left = operandStack.Pop();
                    if(arg == "*")
                    {
                        left = left * right;
                    }
                    else if(arg == "/")
                    {
                        left = left / right;
                    }
                    else if(arg == "+")
                    {
                        left = left + right;
                    }
                    else if(arg == "-")
                    {
                        left = left - right;
                    }
                    else if(arg == "%")
                    {
                        left = left % right;
                    }
                    operandStack.Push(left);
                }
                    
            }
            Console.WriteLine(operandStack.Pop());
            
        }
    }
}

Close solution

This entry was posted on Tuesday, October 24th, 2017 at 6:00 pm

Leave a Reply

Your email address will not be published. Required fields are marked *