leetcode-470-Implement-Rand10()-Using-Rand7()

TOREVIEW

描述


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().

Follow up:

  • What is the expected value for the number of calls to rand7() function?
  • Could you minimize the number of calls to rand7()?

Example 1:

1
2
Input: n = 1
Output: [2]

Example 2:

1
2
Input: n = 2
Output: [2,8]

Example 3:

1
2
Input: n = 3
Output: [3,8,10]

Constraints:

  • 1 <= n <= 105

分析


通过 rand7() 实现 rand10(). 这是一道数学题,找规律的题目。

解决方案1(Java)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 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() {
while (true) {
int num = (rand7() - 1) * 7 + rand7();
if (num <= 40) {
return num % 10 + 1;
}
}
}
}

解决方案2(Golang)


1
2
3
4
5
6
7
func rand10() int {
result := 50
for result > 40 {
result = (rand7() - 1) * 7 + rand7()
}
return result % 10 + 1
}

题目来源