#150. Evaluate Reverse Polish Notation
/**
* @param {string[]} tokens
* @return {number}
*/
var evalRPN = function (tokens) {
const operators = {
"+": (a, b) => a + b,
"-": (a, b) => a - b,
"*": (a, b) => a * b,
"/": (a, b) => Math.trunc(a / b)
}
let stack = []
for (let token of tokens) {
if (token in operators) {
let b = stack.pop()
let a = stack.pop()
stack.push(
operators[token](a, b)
)
}
else {
stack.push(Number(token))
}
}
return stack[0]
};
Cool question but remember you have to pop b
first before a
from stack. Because a
are usually the bigger numbers and the reverse polish notation is arranged in the order that makes a
bigger.
e.g., ["3", "1", "-"]
Here 3 is at the stack's bottom, so popping it, b would be 1 since it is at top or right and a is 3.
ย