[LeetCode] 470. Implement Rand10() Using Rand7()

题目描述

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]

Note:

rand7 is predefined.
Each testcase has one argument: n, the number of times that rand10 is called.

rand7 返回均匀分布的1到7,要求根据rand7 实现一个rand10, 要求返回均匀分布的1到10。
解决思路是先构建一个randN, N 要求是 10 的整数倍。由randN % 10 可以得到rand10。
由rand7 可以得到 rand49 , rand49 通过过滤掉大于等于40 的可以得到 rand40, 进而可以得到rand10。综上,解决思路如下:
rand7 -> rand49 -> rand40 -> rand10
此解决方案可以推广到所有randN 生成randM (N < M) 的场景。

C++ 实现

// 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() {
        const int num = rand40();
        return num % 10 + 1;
    }
private:
    // return 0 ~ 48 randomly 
    int rand49()
    {
        return 7 * (rand7() - 1) + rand7() - 1;
    }
    // return 0 ~ 39 randomly
    int rand40()
    {
        int num = rand49();
        while(num >= 40)
        {
            num = rand49();
        }
        return num;
    }
};
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页