当前位置:网站首页>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
边栏推荐
- 超分之TDAN
- Solution of Navicat connecting Oracle library is not loaded
- How does matlab draw the curve of known formula and how does excel draw the function curve image?
- RPC核心概念理解
- Self use learning notes - connected and non connected access to database
- Use of shell cut command
- 双指针进阶--leetcode题目--盛最多水的容器
- Detailed explanation of C webpai route
- Matlab / Simulink simulation of double closed loop DC speed regulation system
- Shell-awk命令的使用
猜你喜欢

Double pointer advanced -- leetcode title -- container with the most water

Detailed explanation of C webpai route

Use of five routing guards
![[ES6] promise related (event loop, macro / micro task, promise, await / await)](/img/69/ea3ef6063d373f116a44c53565daa3.png)
[ES6] promise related (event loop, macro / micro task, promise, await / await)

Further study of data visualization

Signalr can actively send data from the server to the client

双指针进阶--leetcode题目--盛最多水的容器

ClickHouse-表引擎

1-4 configuration executable script of nodejs installation

Collection of common SQL statements
随机推荐
Construction of functions in C language programming
基于51单片机红外无线通讯仿真
Generation of barcode and QR code
Collection of common SQL statements
线性代数感悟之1
Oninput one function to control multiple oninputs (take the contents of this input box as parameters) [very practical, very practical]
Clickhouse SQL operation
Your brain expands and shrinks over time — these charts show how
JS, entries(), keys(), values(), some(), object Assign() traversal array usage
ClickHouse-表引擎
ASP. NET CORE3. 1. Solution to login failure after identity registers users
Signalr can actively send data from the server to the client
嵌入式系统中,FLASH中的程序代码必须搬到RAM中运行吗?
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
El date picker limits the selection range from the current time to two months ago
Detailed explanation of C webpai route
QT modification UI does not take effect
ASP. Net core JWT certification
Summary of common websites
Halo 开源项目学习(二):实体类与数据表