LC.P470[用Rand7()实现Rand10()]

方法一:数学

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
class Solution extends SolBase {
public int rand10() {
int first, second;
while ((first = rand7()) > 6); // 拒绝7,对[1,6]采样,把奇数和偶数作为采样结果,每种概率为0.5
while ((second = rand7()) > 5); // 拒绝6,7,对[1,5]采样,有五种结果,每种概率为0.2
return (first & 1) == 1 ? second : 5 + second;
}
}