首页 > 其他 > 详细

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

时间:2021-09-05 22:56:00      阅读:37      评论:0      收藏:0      [点我收藏+]

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理解

原文:https://www.cnblogs.com/stepping/p/15229318.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!