Valid operators are +, -, *, and /. Each operand may be an integer or another expression.
Note that division between two integers should truncate toward zero.
It is guaranteed that the given RPN expression is always valid. That means the expression would always evaluate to a result, and there will not be any division by zero operation.
- first thing is to understand how RPN works
- takes in an operation
- then takes following two values
- perform operation
- return result
- use a stack to store values until operand is encountered
- use a map with operand as a key and associated operation as a function
Solution
// from solutions// https://leetcode.com/problems/evaluate-reverse-polish-notation/solutions/486566/javascript-stack-solution/// using stack to parse out numbers, when an operand is encountered, pop off two values from the stack and execute the function assigned in the object
// after performing the operation, the value is pushed back into the stack and repeated until the loop endsfunctionevalRPN(tokens) {conststack= [];constops= {"+": (a, b) => a + b,"-": (a, b) => a - b,"*": (a, b) => a * b,"/": (a, b) => (a / b >=0?Math.floor(a / b) :Math.ceil(a / b)), };for (constelof tokens) {if (ops[el]) {constsecondVal=stack.pop();constfirstVal=stack.pop();constoperation= ops[el](firstVal, secondVal);stack.push(operation); } else {stack.push(Number(el)); } }returnstack.pop();}