题目描述
已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
不要使用系统的 Math.random() 方法。
分析
- 得到1-40 41-49舍弃
- 对于大于40的数,(大于40的随机数−40−1)∗7+rand7()
- 可以得到 1-631−63 之间的随机数,只要舍弃 33 个即可,那对于这 33 个舍弃的,还可以再来一轮:(大于60的随机数−60−1)∗7+rand7()
- 这样我们可以得到 1-211−21 之间的随机数,只要舍弃 11 个即可。
代码
/**
* 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() {
while (true){
int num = (rand7() - 1) * 7 + rand7();
// 如果在40以内,那就直接返回
if(num <= 40) return 1 + num % 10;
// 说明刚才生成的在41-49之间,利用随机数再操作一遍
num = (num - 40 - 1) * 7 + rand7();
if(num <= 60) return 1 + num % 10;
// 说明刚才生成的在61-63之间,利用随机数再操作一遍
num = (num - 60 - 1) * 7 + rand7();
if(num <= 20) return 1 + num % 10;
}
}
}