470. 用 Rand7() 实现 Rand10() 力扣(中等) rand理解

470. 用 Rand7() 实现 Rand10()

已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。

不要使用系统的 Math.random() 方法。

 

示例 1:

输入: 1
输出: [7]

题解:

代码:

// 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 x;
    while(1)
    {
        x=((rand7()-1)*7+rand7()-1);    // 构建两位数的7进制,包含了[1,10],等概率
        if(x>=1 && x<=10) break;
    }
    return x;
    }
};

 

470. 用 Rand7() 实现 Rand10() 力扣(中等) rand理解

上一篇:Activity生命周期和启动模式


下一篇:AI打造时尚漂亮的几何图案背景