LeetCode-150.Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

 public int EvalRPN(string[] tokens)
        {
            Stack<int> num = new Stack<int>();
            int a,b;
            foreach (string item in tokens)
            {
                if (int.TryParse(item, out a))
                {
                    num.Push(a);
                }
                else
                {
                    a = num.Pop();
                    b = num.Pop();
                    if (item=="+")
                        num.Push(a + b);
                    else if(item == "-")
                        num.Push(b - a);
                    else if (item == "*")
                        num.Push(a* b);
                    else  
                        num.Push(b/a);
                }
            }
            return num.Pop();
        }


你可能感兴趣的:(LeetCode,stack)