470. 用 Rand7 实现 Rand10
- 原题链接:
- 完成情况:
- 解题思路:
- 参考代码:
原题链接:
470. 用 Rand7() 实现 Rand10()
https://leetcode.cn/problems/implement-rand10-using-rand7/description/
完成情况:
解题思路:
解题思路:
其实这道题就是典型的数学问题吧,通过已知的rand7()*rand()去达到想要的倍数,然后再通过%n,去实现均等分成多少份,
只要确保{rand7()*rand()*rand7()*rand()} % n 是对应成比例的即可。
参考代码:
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
class Solution extends SolBase {
public int rand10() {
int a,b,index;
while(true){
a = rand7();
b = rand7();
index = b + (a - 1)*7;
if(index <= 40){
return 1+(index-1)%10;
}
a = index - 40;
b = rand7();
index = b + (a - 1)*7;
if(index <= 60){
return 1+(index - 1)%10;
}
a = index - 60;
b = rand7();
index = b+(a-1) * 7;
if(index <= 20){
return 1+(index - 1)%10;
}
}
}
}