首页 > 其他 > 详细

LC 470. Implement Rand10() Using Rand7()

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!