Kotlin Leetcode - 12. Integer to Roman
class Solution {
fun threeSum(nums: IntArray): List<List<Int>> {
}
}
解題思路
這一題考的是字串處理
我們可以將羅馬數字用一個 List 儲存起來
然後跑一次迴圈將數字轉換成字串
Kotlin 參考解答
class Solution {
fun intToRoman(num: Int): String {
val romanList = 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"
)
var number = num
var index = 0
var str = ""
while (number != 0) {
if (number >= romanList[index].first) {
val romanValue = romanList[index]
number -= romanValue.first
str += romanValue.second
} else {
index++
}
}
return str
}
}
回到 leetcode 列表