Poison

470. Implement Rand10() Using Rand7()

1
2
3
4
5
6
7
8
9
10
class Solution extends SolBase {
public int rand10() {
while (true) {
int random = (rand7() - 1) * 7 + (rand7() - 1); // [0, 6] * 7 + [0, 6] -> [0, 48]
if (random >= 0 && random <= 39) {
return random % 10 + 1; // 注意结果要求返回 [1, 10] 范围中的数字,所以此处加 1
}
}
}
}
Reference

470. Implement Rand10() Using Rand7()