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:
parent
7ee0a7cce6
commit
989f2b071e
1 changed files with 36 additions and 0 deletions
36
kt/integer-to-roman.kt
Normal file
36
kt/integer-to-roman.kt
Normal 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()
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue