URL: https://leetcode.com/problems/integer-to-roman/ Signed-off-by: Matej Focko <me@mfocko.xyz>
36 lines
944 B
Kotlin
36 lines
944 B
Kotlin
class Solution {
|
|
companion object {
|
|
private val SYMBOLS: List<Pair<Int, String>> =
|
|
listOf(
|
|
1000 to "M",
|
|
900 to "CM",
|
|
500 to "D",
|
|
400 to "CD",
|
|
100 to "C",
|
|
90 to "XC",
|
|
50 to "L",
|
|
40 to "XL",
|
|
10 to "X",
|
|
9 to "IX",
|
|
5 to "V",
|
|
4 to "IV",
|
|
1 to "I",
|
|
)
|
|
}
|
|
|
|
fun intToRoman(num: Int): String =
|
|
SYMBOLS.fold(num to StringBuilder()) { (num, sb), (value, symbol) ->
|
|
when (num) {
|
|
0 -> num to sb
|
|
else -> {
|
|
val count = num / value
|
|
|
|
(1..count).forEach {
|
|
sb.append(symbol)
|
|
}
|
|
|
|
num % value to sb
|
|
}
|
|
}
|
|
}.second.toString()
|
|
}
|