Simple C# solution


  • 0
    C
    
    int result = 0;
    
                Stack<int> myStack = new Stack<int>();
    
                for (int i = 0; i < tokens.Length; i++)
                {
                    int res = 0;
                    if (Int32.TryParse(tokens[i], out res))
                    {
                        // the token is a value.
                        myStack.Push(Convert.ToInt32(tokens[i]));
                    }
                    else
                    {
                        // the token is an operator.
                        if (myStack.Count < 2)
                        {
                            // fewer elements on the stack.
                            result = 0;
                            myStack.Push(result);
                        }
                        else
                        {
                            // pop the 2 values from the stack.
                            int firstOperand = myStack.Pop();
                            int secondOperand = myStack.Pop();
    
                            switch (tokens[i])
                            {
                                case "+":
                                    result = firstOperand + secondOperand;
                                    break;
                                case "-":
                                    result = secondOperand - firstOperand;
                                    break;
                                case "*":
                                    result = firstOperand * secondOperand;
                                    break;
                                case "/":
                                    result = secondOperand / firstOperand;
                                    break;
                            }
    
                            // push the new value on the stack.
                            myStack.Push(result);
                        }
                    }
                }            
    
                return myStack.Pop();
    
    

Log in to reply
 

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