Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators is + , - , * , / . Each operand is an integer or another expression.
Some Examples:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
Stack only saves numbers, encounters operator, pops two numbers, calculates them, and then deposits the results in a stack. The first element of the last stack is the answer.
Note-the difference from/to the first pop value is on the right side of the operator.
Public intEVALRPN (string[] tokens) {Stack<int> stack =Newstack<int>(); for(inti =0;i< tokens. Count (); i++) { if(Tokens[i] = ="+") {stack. Push (Stack. Pop ()+stack. Pop ()); } Else if(Tokens[i] = ="-") {stack. Push (-1*stack. Pop () +stack. Pop ()); } Else if(Tokens[i] = ="*") {stack. Push (Stack. Pop ()*stack. Pop ()); } Else if(Tokens[i] = ="/") { intA =stack. Pop (); intb =stack. Pop (); Stack. Push (b/a); } Else{stack. Push (Int32.Parse (tokens[i)); } } returnstack. Peek (); }
Evaluate Reverse Polish Notation questioneditorial Solution