C# implementaion


  • 0
    C

    C# implementation

    Typical stack way. If you just want to pass OJ, then change double type to int.

            public double EvalRPN(string[] tokens)
            {
                Stack<double> stack = new Stack<double>();
    
                foreach (string s in tokens)
                {
                    if (s == "+" || s == "-" || s == "*" || s == "/")
                    {
                        double b = stack.Pop();
                        double a = stack.Pop();
                        double r = Calc(a, b, s);
                        stack.Push(r);
                    }
                    else
                    {
                        stack.Push(double.Parse(s));
                    }
                }
    
                return stack.Pop();
            }
    
            private double Calc(double a, double b, string op)
            {
                switch (op)
                {
                    case "+":
                        return a + b;
                    case "-":
                        return a - b;
                    case "*":
                        return a * b;
                    case "/":
                        return a / b;
                    default:
                        return 0;
                }
            }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.