Leetcode Practice

LC 150. Evaluate Reverse Polish Notation

Last updated
Reading time
1 min read

The problem

Solution

The stack trick with this one came to me pretty quickly, but where I screwed up was the round toward zero for negative numbers. I tried Math.floor, but Math.trunc was what I needed to use because it effectively rounds toward zero by truncating decimal places. Lastly, I tried parseInt by itself at first but with zero being falsey, I had to add Number.isInteger.

Besides these aspects of the problem, I used eval to calculate from directly from the string. Also, because division requires the first number popped to be the divisor, I had to store it since its the first value popped but the second value that appears in the calculation.

function evalRPN(tokens: string[]): number {
  let stack = []
  for (let t of tokens) {
    if (Number.isInteger(parseInt(t))) {
      stack.push(t)
    } else {
      let second = stack.pop()
      stack.push(Math.trunc(eval(`${stack.pop()} ${t} ${second}`)))
    }
  }
  return stack[0]
}