0%

leetcode 470 Solution

代码解析

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.demo.s470;


/**
* 给定方法 rand7 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。
*
* 你只能调用 rand7() 且不能调用其他方法。请不要使用系统的 Math.random() 方法。
*
* 每个测试用例将有一个内部参数 n,即你实现的函数 rand10() 在测试时将被调用的次数。请注意,这不是传递给 rand10() 的参数。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode.cn/problems/implement-rand10-using-rand7
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class SolBase {
public int rand7() {
return (int)(Math.random() * 10 % 7);
}
}
public class Solution extends SolBase {

//随机产生01
private int random01() {
int i = rand7();
//通过4分割 123 -> 0 ;567 -> 1 如果刚好是4 就重来
if(i< 4) {
return 0;
} else if( i > 4){
return 1;
} else {
return random01();
}
}

//随机10 通过4位二进制标识
public int rand10() {
int x = 0;
//
for(int i = 0; i < 4;i++) {
int i1 = random01();
int i2 = i1 << i; //左移i位
x = x + i2;
}
//如果超出了 [1, 10] 重新来
if(x>=1 && x<= 10) {
return x;
} else {
return rand10();
}
}
}