/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
// 弄不懂,我也是直接看答案的,推荐这篇:
// https://leetcode-cn.com/problems/implement-rand10-using-rand7/solution/cong-zui-ji-chu-de-jiang-qi-ru-he-zuo-dao-jun-yun-/
// 第二个a=num-40为rand9(),第二个num为rand63(),
// 第三个a= num - 60为rand3(),第三个num为rand21()
//
// 执行用时:7 ms, 在所有 Java 提交中击败了99.34%的用户
// 内存消耗:43.6 MB, 在所有 Java 提交中击败了32.92%的用户
class Solution extends SolBase {
public int rand10() {
while (true) {
int num = (rand7() - 1) * 7 + rand7();
if (num <= 40) return num % 10 + 1;
}
}
}
// 第二个a=num-40为rand9(),第二个num为rand63(),
// 第三个a= num - 60为rand3(),第三个num为rand21()
//
// 执行用时:7 ms, 在所有 Java 提交中击败了99.34%的用户
// 内存消耗:43.7 MB, 在所有 Java 提交中击败了24.28%的用户
class Solution extends SolBase {
public int rand10() {
while (true) {
int a = rand7();
int b = rand7();
int num = (a - 1)*7 + b;
if (num <= 40) return num % 10 + 1;
a = num - 40;
b = rand7();
num = (a - 1)*7 + b;
if (num <= 60) return num % 10 + 1;
a = num - 60;
b = rand7();
num = (a - 1)*7 + b;
if (num <= 20) return num % 10 + 1;
}
}
}