470. Implement Rand10() Using Rand7()
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.
Follow up:
- What is the expected value for the number of calls to
rand7()
function? - Could you minimize the number of calls to
rand7()
?
题目:由均匀分布rand7
实现均匀分布rand10
。
思路:首先利用rand7
等概率生成1-49的数,如果生成的数num
小于等于40,则取余10加1,可等概率生成1-10的数,否则重新生成num
。
// 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() {
int num = (rand7()-1)*7 + rand7();
if(num <= 40)
return num % 10 + 1;
else
return rand10();
}
};