Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub

Kotlin Leetcode - 12. Integer to Roman

題目連接:https://leetcode.com/problems/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 列表