admin管理员组文章数量:1637231
Given a function rand7
which generates a uniform random integer in the range 1 to 7, write a function rand10
which generates a uniform random integer in the range 1 to 10.
Do NOT use system's Math.random()
.
Example 1:
Input: 1 Output: [7]
Example 2:
Input: 2 Output: [8,4]
Example 3:
Input: 3 Output: [8,1,10]
Note:
rand7
is predefined.- Each testcase has one argument:
n
, the number of times thatrand10
is called.
已知Rand7,求Rand10。
思路:
根据Rand7,求得0~10n-1的随机数,包含0,不包含10*n - 1,假设当前求得0~10*n-1中的随机数为m,则m%10即为0~9中的随机数,m%10 + 1即为1~10中的随机数,即为所求。
7*(Rand7() - 1) = {0, 7, 14, 21, 28, 35, 42},这7个数等概率
7*(Rand7() - 1) + Rand() - 1表示{0,1,2,3,4,5,6,......40, ... 48},这49个数等概率
再将这49个数分为两部分, {0, 1, 2, ... , 39}和{40, 41, .., 48},如果生成的数处于第2部分,再将第二部分等概率分到第1部分,总概率 =
程序如下所示:
/**
* 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 num = 0;
while (true){
num = 7*(rand7() - 1) + rand7() - 1;
if (num < 40){
return (num%10) + 1;
}
}
}
}
本文标签: implement
版权声明:本文标题:470. Implement Rand10() Using Rand7() 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729233426a1191715.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论