码迷,mamicode.com
首页 > 其他好文 > 详细

LC 470. Implement Rand10() Using Rand7()

时间:2019-01-01 18:18:18      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:amp   col   ons   orm   discus   code   output   The   ret   

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()

标签:amp   col   ons   orm   discus   code   output   The   ret   

原文地址:https://www.cnblogs.com/ethanhong/p/10205371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!