1. 程式人生 > >LC 470. Implement Rand10() Using Rand7()

LC 470. Implement Rand10() Using Rand7()

() fast discus pub inpu leetcode c++ write rate

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
Output: [8,1,10]

Runtime: 88 ms, faster than 42.31% of C++ online submissions for Implement Rand10() Using Rand7().

不會做,好題,是一道極限近似題。

https://leetcode.com/problems/implement-rand10-using-rand7/discuss/150301/Three-line-Java-solution-the-idea-can-be-generalized-to-%22Implement-RandM()-Using-RandN()%22

class Solution {
public
: int rand10() { int ret = 40; while(ret >= 40) { ret = 7 *(rand7()-1) + rand7()-1; } return ret%10+1; } };

LC 470. Implement Rand10() Using Rand7()