Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 470. Implement Rand10() Using Rand7()

題目連接

/**
 * The rand7() API is already defined in the parent class SolBase.
 * fun rand7(): Int {}
 * @return a random integer in the range 1 to 7
 */
class Solution {
    fun fizzBuzz(n: Int): List<String> {
	}
}

解題思路

純數學題

需要對機率有一點熟悉

Kotlin 參考解答

點擊展開解答
class Solution : SolBase() {
    fun rand10(): Int {
        while(true) {
            val a = rand7()
            val b = rand7()
            val idx = 7 * (a - 1) + b
            if (idx <= 40) {
                return 1 + (idx - 1) % 10;
            }
        }
    }
}

回到 leetcode 列表