1、描述
已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
不要使用系统的 Math.random() 方法。
来源:力扣(LeetCode)
链接:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2、关键字
随机数生成随机数,
3、思路
4、notes
int num = (rand7() - 1) * 7 + rand7();
num % 10 + 1;
5、复杂度
6、code
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution {
public:
int rand10() {
while(true){
int num = (rand7() - 1) * 7 + rand7(); // 1-49
if(num <=40) return num % 10 + 1; // 拒绝采样
num = (num - 40 - 1) * 7 + rand7(); // 使用41-49之间的1-9个数,造出来:1-63
if(num <= 60) return num% 10 + 1; // 拒绝采样,只要1-60之间的
num = (num - 60 - 1) * 7 + rand7(); // 1-21
if(num <= 20) return num % 10 + 1;
}
}
};