LeetCode Entry

150. Evaluate Reverse Polish Notation

17.12.2022 medium 2022 kotlin

fun evalRPN(tokens: Array): Int = with(Stack()) {

150. Evaluate Reverse Polish Notation medium

https://t.me/leetcode_daily_unstoppable/54

blog post

    fun evalRPN(tokens: Array<String>): Int = with(Stack<Int>()) {
        tokens.forEach {
            when(it) {
                "+" -> push(pop() + pop())
                "-" -> push(-pop() + pop())
                "*" -> push(pop() * pop())
                "/" -> with(pop()) { push(pop()/this) }
                else -> push(it.toInt())
            }
      }
      pop()
    }

Reverse polish notations made explicitly for calculation using stack. Just execute every operation immediately using last two numbers in the stack and push the result.

  • be aware of the order of the operands

Space: O(N), Time: O(N)