470. Implement Rand10() Using Rand7()

1
2
3
4
5
6
7
8
9
10
11
class Solution extends SolBase {
public int rand10() {
while (true) {
// rand7() return: [1, 7]
int randomValue = (rand7() - 1) * 7 + (rand7() - 1); // [0, 6] * 7 + [0, 6] -> [0, 48]
if (randomValue < 40) {
return randomValue % 10 + 1; // 注意结果要求返回 [1, 10] 范围中的数字,所以此处加 1
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution extends SolBase {
public int rand10() {
// 给定方法 rand7 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。

int x;
do {
x = rand7() * 7 + rand7(); // [8, 56]
// [8, 14]
// [15, 21]
// [22, 28]
// ...
} while (!(x >= 11 && x <= 50));

return x % 10 + 1; // 注意结果要求返回 [1, 10] 范围中的数字,所以此处加 1
}
}

References

470. Implement Rand10() Using Rand7()