LC 470. 用 Rand7() 实现 Rand10() (概率)

2022-01-13 15:00:34 浏览数 (1)

思路

贴一个力扣大佬的题解吧 力扣题解 这个概率统计和拒绝采样之前没见过

代码语言:javascript复制
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7

class Solution {
public:
    int rand10() {
        int n = (rand7() - 1) * 7   rand7();
        while (n > 40) {
            n = (rand7() - 1) * 7   rand7();
        }
        return n % 10   1;
    }
};

0 人点赞