-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSolution.java
132 lines (114 loc) · 3.13 KB
/
Solution.java
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package leetcode.algo.misc.leet_zh_470;
public class Solution extends SolBase {
/*
*
*
*
*
* 计算两个rand7()和的个位,两个数用a b表示,即( rand7() + rand7() ) % 10
枚举如下:
a 1 2 3 4 5 6 7
b
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9 0
4 5 6 7 8 9 0 1
5 6 7 8 9 0 1 2
6 7 8 9 0 1 2 3
7 8 9 0 1 2 3 4
去掉右上角的
6 7 8
7 8 9
8 9 0 后
每个数字的出现次数为4次,0-9的概率相同
所以程序思路就很明了,当结果扫到右上角的时候进行递归调用,直到输出其他结果
a=rand7(); b=rand7();
if(a>4&&b<4) return rand10();
else return (a+b)%10+1;
平均调用2.3次rand7()
* */
public int rand10Tow() {
/*
*
* 两个数用a b表示,即( rand7() + rand7() ) % 10
枚举如下:
a 0 1 2 3 4 5 6
b
0 0 1 2 3 4 5 6
1 1 2 3 4 5 6 7
2 2 3 4 5 6 7 8
3 3 4 5 6 7 8 9
4 4 5 6 7 8 9 0
5 5 6 7 8 9 0 1
6 6 7 8 9 0 1 2
除去 右上角
4 5 6
5 6 7
6 7 8
每个数字的出现次数为4次,0-9的概率相同
a 0 1 2 3 4 5 6
0
0 1
b 0 1 2
0 0 1 2 3 4 5 6
1 1 2 3 4 5 6 7
2 2 3 4 5 6 7 8
3 3 4 5 6
4 4 5 6 7
5 5 6 7 8
6 6 7 8 9
7 8 9
8 9
9
* */
int a = rand7();
int b = rand7();
while (a > 3 && b < 3)
return rand10();
return (a + b) % 10;
}
public int rand10() {
/*
*
* 执行用时 : 7 ms, 在Implement Rand10() Using Rand7()的Java提交中击败了92.50% 的用户
* 内存消耗 : 36.4 MB, 在Implement Rand10() Using Rand7()的Java提交中击败了100.00% 的用户
* */
/*
*
* 计算两个rand7()和的个位,两个数用a b表示,即( rand7() + rand7() ) % 10
枚举如下:
a 1 2 3 4 5 6 7
b
1 2 3 4 5 6 7 8
2 3 4 5 6 7 8 9
3 4 5 6 7 8 9 0
4 5 6 7 8 9 0 1
5 6 7 8 9 0 1 2
6 7 8 9 0 1 2 3
7 8 9 0 1 2 3 4
去掉右上角的
6 7 8
7 8 9
8 9 0 后
每个数字的出现次数为4次,0-9的概率相同
* */
int a, b;
do {
a = rand7();
b = rand7();
} while (a > 4 && b < 4);
return (a + b) % 10 + 1;
}
public static void main(String[] args) {
Solution ss = new Solution();
System.out.println(ss.rand10());
System.out.println(ss.rand10());
System.out.println(ss.rand10());
System.out.println(ss.rand10());
System.out.println(ss.rand10());
System.out.println(ss.rand10());
System.out.println(ss.rand10());
System.out.println(ss.rand10());
System.out.println(ss.rand10());
}
}