ID | Title | Difficulty | |
---|---|---|---|
Loading... |
470. Implement Rand10() Using Rand7()
Medium
LeetCode
Math, Rejection Sampling, Randomized, Probability and Statistics
Problem
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:
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 <= 10^5
Code
/**
* 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 v1 = rand7();
int v2 = rand7();
while(v1 > 5) v1 = rand7();
while(v2 == 7) v2 = rand7();
return v2 <= 3 ? v1 : v1 + 5;
}
}
按 <- 键看上一题!
469. Convex Polygon
按 -> 键看下一题!
473. Matchsticks to Square