The rand7() API is already defined in the parent class SolBase. public int rand7(); @return a random integer in the range 1 to 7

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
* @lc app=leetcode.cn id=470 lang=java
*
* [470] 用 Rand7() 实现 Rand10()
*/

// @lc code=start
/**
* 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 {
/**
* (randX() - 1) * Y + randX() = randX*Y()
* 通过这个算式计算出来rand49, 然后取到了41-49就重复取
*/
public int rand10() {
int rand49;
while (true) {
rand49 = (rand7() - 1) * 7 + rand7();
if (rand49 <= 40) return rand49 % 10 + 1;
int rand63 = (rand49 - 40 - 1) * 7 + rand7();
if (rand63 <= 60) return rand63 % 10 + 1;
int rand21 = (rand63 - 60 - 1) * 7 + rand7();
if (rand21 <= 20) return rand21 % 10 + 1;
}
}
}
// @lc code=end

Comments
Recent Posts
进程树
进程管理
Categories
Website Info
Article Count :
3
Total Word Count :
4.7k
Unique Visitors :
Page Views :
Last Update :