当前位置:网站首页>470. 用 Rand7() 实现 Rand10()
470. 用 Rand7() 实现 Rand10()
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
给定方法 rand7 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。
你只能调用 rand7() 且不能调用其他方法。请不要使用系统的 Math.random() 方法。
每个测试用例将有一个内部参数 n,即你实现的函数 rand10() 在测试时将被调用的次数。请注意,这不是传递给 rand10() 的参数。
示例 1:
输入: 1
输出: [2]
示例 2:
输入: 2
输出: [2,8]
示例 3:
输入: 3
输出: [3,8,10]
二、解题
拒绝采样
/** * The rand7() API is already defined in the parent class SolBase. * public int rand7(); * @return a random integer in the range 1 to 7 */
class Solution extends SolBase {
public int rand10() {
int maxNum = Integer.MAX_VALUE;
while(maxNum > 40){
maxNum = rand7() + (rand7()-1) * 7;
}
return 1+maxNum%10;
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://blog.csdn.net/hequnwang10/article/details/124308420
边栏推荐
- .Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
- Use of shell cut command
- C语言函数详解
- How to sort the numbers with text in Excel from small to large instead of the first number
- Bottom processing of stack memory in browser
- 1-1 NodeJS
- 2.Electron之HelloWorld
- 1-3 nodejs installation list configuration and project environment
- JS to find the character that appears three times in the string
- matlab如何绘制已知公式的曲线图,Excel怎么绘制函数曲线图像?
猜你喜欢
随机推荐
Some problems encountered in recent programming 2021 / 9 / 8
Manually implement call, apply and bind functions
1-4 configuration executable script of nodejs installation
node中,如何手动实现触发垃圾回收机制
Using quartz under. Net core -- a simple trigger of [7] operation and trigger
Header built-in object
開期貨,開戶雲安全還是相信期貨公司的軟件?
[related to zhengheyuan cutting tools]
. net cross platform principle (Part I)
Summary of common websites
How to manually implement the mechanism of triggering garbage collection in node
How to sort the numbers with text in Excel from small to large instead of the first number
XTask与Kotlin Coroutine的使用对比
常用SQL语句总结
Construction of functions in C language programming
读《Software Engineering at Google》(15)
Exercise: even sum, threshold segmentation and difference (two basic questions of list object)
双闭环直流调速系统matlab/simulink仿真
EF core in ASP Generate core priority database based on net entity model
Tdan over half