Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.
Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().
Example 1:
Input: n = 1 Output: [2]
Example 2:
Input: n = 2 Output: [2,8]
Example 3:
Input: n = 3 Output: [3,8,10]
Constraints:
1 <= n <= 105
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 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。
你只能调用 rand7() 且不能调用其他方法。请不要使用系统的 Math.random() 方法。
每个测试用例将有一个内部参数 n,即你实现的函数 rand10() 在测试时将被调用的次数。请注意,这不是传递给 rand10() 的参数。
示例 1:
输入: 1 输出: [2]
示例 2:
输入: 2 输出: [2,8]
示例 3:
输入: 3 输出: [3,8,10]
提示:
1 <= n <= 105
进阶:
rand7()调用次数的 期望值 是多少 ?- 你能否尽量少调用
rand7()?
| Language | Runtime | Memory | Submission Time |
|---|---|---|---|
| typescript | 120 ms | 50.6 MB | 2023/05/18 11:37 |
/**
* The rand7() API is already defined for you.
* function rand7(): number {}
* @return a random integer in the range 1 to 7
*/
function rand10(): number {
let num = Infinity;
while (num > 40) {
num = (rand7() - 1) * 7 + rand7();
}
return num % 10 + 1;
};No notes