lotus

贵有恒何必三更眠五更起 最无益只怕一日曝十日寒

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

1. 题目

 

https://leetcode.cn/problems/implement-rand10-using-rand7/submissions/425373186/

 

2. 解法

思路

这道题的要求是用rand7()函数来生成1到10之间的均匀随机数。

一种可能的解法是使用拒绝采样的方法,

  • 即先用rand7()函数生成两个随机数,
  • 然后将它们组合成一个1到49之间的随机数,
  • 如果这个数在1到40之间,就返回它对10取余加1的结果,否则就重新生成。

这样可以保证每个数字出现的概率都是相同的。

 

规律 

 

 rand7->rand9

  • 7*7 49   
  • 45 划线
  • 取模 

rand6 -> rand13

  • 6*6  36
  • 26划线
  • 取模 

 

 

具体实现

class Solution {
    public int rand10() {
        int num = (rand7() - 1) * 7 + rand7(); // generate a random number from 1 to 49
        while (num > 40) { // reject the numbers that are larger than 40
            num = (rand7() - 1) * 7 + rand7();
        }
        return num % 10 + 1; // return the result from 1 to 10
    }
}

  

3. 总结

posted on 2023-04-17 17:58  白露~  阅读(8)  评论(0编辑  收藏  举报