URL: https://leetcode.com/problems/evaluate-reverse-polish-notation/ Signed-off-by: Matej Focko <me@mfocko.xyz>
29 lines
799 B
Kotlin
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()
|
|
}
|