LeetCode 470 用Rand7()实现Rand10()

题目链接:LeetCode 470 用Rand7()实现Rand10()

题目大意:

题解:
只需要能够满足等概率的生成\(10\)个不同的数即可,具体的生成方法可以有很多种。
我们可以调用两次\(Rand7()\),那么可以生成\([1, 49]\)之间的随机整数,我们只用到其中的前\(40\)个用来实现\(Rand10()\),而拒绝剩下的\(9\)个数。

class Solution {
public:
    int rand10() {
        int ans;
        do {
            ans = rand7() + (rand7() - 1) * 7;
        } while (ans > 40);
        return 1 + (ans - 1) % 10;
    }
};
posted @ 2022-02-06 14:23  ZZHHOOUU  阅读(28)  评论(0编辑  收藏  举报