LC 470. Implement Rand10() Using Rand7()

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;
    }
};
原文地址:https://www.cnblogs.com/ethanhong/p/10205371.html