Given a function rand7
which generates a uniform random integer in the range 1 to 7, write a function rand10
which generates a uniform random integer in the range 1 to 10.
Do NOT use system's Math.random()
.
Example 1:
Input: 1
Output: [7]
Example 2:
Input: 2
Output: [8,4]
Example 3:
Input: 3 The Output: [8,1,10]
thinking: meaning of the questions is relatively simple, with rand7 () to achieve rand10 (). rand7 () produced is 1-7 all integers, rand10 () We hope to have that all the integers 1-10. One thing is obvious, if we only call once rand7 (),
we can not produce 8,9,10 three digits. So obviously we should call at least 2 times. call 2 times range of numbers will be generated is 1-49, note that not 1-14. (multiplication than addition) 1-49 If we can discard 41-49. So at this time
we have is 1-40 and can produce subject requirements of uniform random. Thus, if the subject is required to produce 1-40 transition at the output is the answer to this generated random number and taking the remainder after 10, 40% to 10 plus 1. Otherwise = 0.
class Solution: def rand10(self): """ :rtype: int """ rand = 41 while rand >= 41: rand = (rand7 () - 1) * 7 + rand7 () return rand%10 +1