Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 3945. Digit Frequency Score

題目連接:https://leetcode.com/problems/digit-frequency-score/

class Solution {
    fun digitFrequencyScore(n: Int): Int {

    }
}

解題思路

這題要用的是將數值的每個數字拆分出來進行加總。

我們可以使用一個 while 迴圈,加上除法和餘數計算進行處理。

不過,如果你使用 Kotlin 字串內建的函數的話

可以將字串拆解成字母,然後使用 digitToInt 轉換成數字的值

最後以 sumOf() 進行加總

Kotlin 參考解答

點擊展開解答
class Solution {
    fun digitFrequencyScore(n: Int): Int {
        var num = n
        var sum = 0
        while (num > 0) {
            val digit = num % 10
            sum += digit
            num /= 10
        }
        return sum
    }
}

使用 digitToInt()sumOf() 的做法如下

class Solution {
    fun digitFrequencyScore(n: Int): Int {
        return n.toString().sumOf { it.digitToInt() }
    }
}

回到 leetcode 列表