LeetCode/kt/evaluate-reverse-polish-notation.kt

29 lines
799 B
Kotlin

class Solution {
private fun getFunction(op: String): (Int, Int) -> Int =
when (op) {
"+" -> Int::plus
"-" -> Int::minus
"*" -> Int::times
"/" -> Int::div
else -> error("invalid operator")
}
fun evalRPN(tokens: Array<String>): Int =
tokens.fold(mutableListOf<Int>()) { stack, token ->
when (token) {
"+", "-", "*", "/" -> {
check(stack.size >= 2)
val r = stack.removeLast()
val l = stack.removeLast()
stack.add(getFunction(token)(l, r))
}
else -> {
stack.add(token.toInt())
}
}
stack
}.last()
}