Question: Evaluate reverse Polish notation
Evaluatethe 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
A simple question, with the help of a stack, can be achieved, the value into the stack, when the operator will be two values out of the stack, after calculation re-stack, so that you can achieve.
Int evalrpn (vector <string> & tokens) {stack <int> stokens; For (INT I = 0; I <tokens. size (); ++ I) {If (tokens [I] = "+" | tokens [I] = "-" | tokens [I] = "*" | tokens [I] = "/") {int X1 = ens. top (); parameter ens. pop (); int X2 = parameter ens. top (); parameter ens. pop (); int X3 = caculate (x1, x2, tokens [I]); // re-entry stack ens after calculation. push (X3);} else {kerberens. push (atoi (tokens [I]. c_str ();} return stokens. top ();}
int caculate(int x1, int x2, string s) { int result; if (s == "+") result = x1 + x2; else if (s == "-") result = x1 - x2; else if (s == "*") result = x1 * x2; else { if (x1 >= x2) result = x1 / x2; else result = x2 / x1; } return result;}
Leetcode: Evaluate reverse Polish notation