当前位置:网站首页>LeetCode-470-用Rand7()实现Rand10()
LeetCode-470-用Rand7()实现Rand10()
2022-06-29 15:26:00 【z754916067】
题目

思路
- 之前做过这种题,虽然已经完全忘记了,还是想不太出来,去看题解了。
- 例如使用rand2求rand4,如果使用(rand2()-1+rand2()),可以计算出其范围在[1,3]之间,虽生成的值确实在[1,4]之间,但不符合条件。
- 但如果是2*(rand2()-1)+rand2(),可以计算出其在[1,4]之间。
- 故很明显,就是要找出把[1,7]化成[1,10]的算式,根据以上经验,总之要先化出[0,x]出来,考虑将rand7()-1,成为[0,6]的值,为让其范围在7的倍数中,将其x7,成为[0,42],为了让左边界为7,再加上rand7(),成为[1,49]
- 此时,可以使用rand7()得到rand49(),且各个概率皆均匀,即12345678910这十个数字是均匀的,虽然相加不为1。
- 那么后续很明显,抛弃所有不为[1,10]或者将获得的所有化成[1,10]即可。
代码
public int rand10() {
while(true){
//用rand7()实现rand10()
int num=0;
num=(rand7() - 1) * 7 + rand7(); //等概率生成[1,49]
if(num>=40) return num%10+1;
}
}
边栏推荐
- Rust Basics
- ImgUtil 图片处理工具类,文字提取,图片水印
- 深度学习网络的训练方式
- Get the width of text component content
- I am 35 years old. Can I change my career to be a programmer?
- Introduction to radar antenna
- 服务器的数据库连不上了【服务已起、防火墙已关、端口已开、netlent 端口不通】
- 极化SAR地表分类
- LeetCode笔记:Weekly Contest 299
- CKS CKA ckad change terminal to remote desktop
猜你喜欢

Lumiprobe reactive dye carboxylic acid: sulfo cyanine7.5 carboxylic acid

Middle order and post order traversal to construct binary tree [recursive partition interval and backtracking splicing subtree + similarity and difference between middle post order and middle pre orde

About sql+nosql: newsql database

雷达基本组成

ImgUtil 图片处理工具类,文字提取,图片水印

Lumiprobe deoxyribonucleic acid alkyne DT phosphimide

Northwestern Polytechnic University attacked by overseas e-mail

Lumiprobe reactive dye miscellaneous dye: BDP FL ceramide

Solution to the problem that the assembly drawing cannot be recognized after the storage position of SolidWorks part drawing is changed

MCS: discrete random variable - binomial distribution
随机推荐
MySQL development specification pdf
这是少了什么依赖嘛?FlinkSql打包运行的时候报错,但是本地idea跑的时候是没问题的,求解,谢
中序和后序遍历构建二叉树[递归划分区间与回溯拼接子树+中后序和中前序的相似与不同]
What is the relationship between synchronized and multithreading
curl: (56) Recv failure: Connection reset by peer
11. application layer data transmission format / port number -bite
极化SAR地表分类
Solution to the problem that the assembly drawing cannot be recognized after the storage position of SolidWorks part drawing is changed
MySQL scheduled full database backup & rolling deletion of backup data before the specified date
Chapter IX app project test (4) test tools
Create an API rapid development platform, awesome!
关于遥感图像解译的思考
上次给我们发福利的 TDesign ,今天讲讲它的开源故事
Is it safe to open a stock account at present? Can I open an account online directly
About sql+nosql: newsql database
Flink SQL task taskmanager memory settings
TDesign, which gave us benefits last time, will tell us its open source story today
Real software testers = "half product + Half development"?
Unity C basic review 29 - Generic delegation (p451)
Alibaba cloud experience Award: use polardb-x and Flink to build a large real-time data screen