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.n
, the number of times that rand10
is called.Follow up:
rand7()
function?rand7()
?使用能够随机生成整数1-7的函数rand7(),来写一个新的函数rand10(),使其能够随机生成整数1-10。
/**
* 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 = (rand7() - 1) * 7 + rand7();
return num <= 40 ? num % 10 + 1 : rand10();
}
}
0470. Implement Rand10() Using Rand7() (M)
原文:https://www.cnblogs.com/mapoos/p/13581717.html