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
With stack, each time an operator encounters an operator, it extracts two numbers from the stack. Then, the number operator extracts the number first, and then puts it back in the stack. When a number is encountered, it is directly put into the stack. Switch does not support string, instead of index.
Public Class Solution { Public Int Evalrpn (string [] tokens) {Stack <String> stack = New Stack <string> (); String Operators = "+ -*/" ; For (String T: tokens ){ If (! Operators. Contains (t) {stack. Push (t );} Else { Int Index =Operators. indexof (t ); Int B = Integer. valueof (stack. Pop ()); Int A = Integer. valueof (stack. Pop ()); Switch (Index ){ Case 0 : Stack. Push (string. valueof ( + B )); Break ; Case 1 : Stack. Push (string. valueof ( - B )); Break ; Case 2 : Stack. Push (string. valueof ( * B )); Break ; Case 3 : Stack. Push (string. valueof ( /B )); Break ;}}} Return Integer. valueof (stack. Pop ());}}