kt: add «12. Integer to Roman»

URL:	https://leetcode.com/problems/integer-to-roman/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-03-05 19:01:30 +01:00
parent 7ee0a7cce6
commit 989f2b071e
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

36
kt/integer-to-roman.kt Normal file
View file

@ -0,0 +1,36 @@
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()
}