Implement Rand10() Using Rand7() — LeetCode 470 Python Solution
- Problem
- #470
- Pattern
- Math and Number Theory
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- n = 1
- Output
- [2]
Python solution
# The rand7() API is already defined for you.
# def rand7():
# @return a random integer in the range 1 to 7
class Solution:
def rand10(self):
"""
:rtype: int
"""
while 1:
i = rand7() - 1
j = rand7()
x = i * 7 + j
if x <= 40:
return x % 10 + 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) or O(1) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 470. Implement Rand10() Using Rand7() is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 470. Implement Rand10() Using Rand7()?
- LeetCode 470. Implement Rand10() Using Rand7() is rated Medium on LeetCode.
- What topics does LeetCode 470. Implement Rand10() Using Rand7() cover?
- LeetCode 470. Implement Rand10() Using Rand7() is tagged Math, Rejection Sampling, Probability and Statistics and Randomized on LeetCode.