470. Implement Rand10() Using Rand7()
LeetCode 470. Implement Rand10() Using Rand7()****
Description
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:
Example 2:
Constraints:
1 <= n <= 105
Tags
Math
Solution
We randomly choose a position via (row-1)*7 + (col-1)
in the table above, and repeat this procedure until we can obtain a number between 1 and 10 rather than '*'.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?