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 列表