Skip to content

Latest commit

 

History

History
37 lines (31 loc) · 1.01 KB

2022-12-17.md

File metadata and controls

37 lines (31 loc) · 1.01 KB

题目

  1. Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

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.

思路

代码

var evalRPN = function(tokens) {
  const stack = []
  for (const token of tokens) {
    if (!(token == '+' || token == '-' || token == '*' || token == '/')) {
      stack.push(parseInt(token))
      continue
    }
    const op2 = stack.pop()
    const op1 = stack.pop()
    if (token == '+') {
      stack.push(op1 + op2)
    } else if (token == '-') {
      stack.push(op1 - op2)
    } else if (token == '*') {
      stack.push(op1 * op2)
    } else {
      stack.push(Math.trunc(op1 / op2))
    }
  }
  return stack.pop()
}