原题如下
https://leetcode-cn.com/problems/implement-rand10-using-rand7/
题解
原理其实就是7进制的数字生成,并且让生成数字的十进制表示的各位是0到9(加1)。
下边的代码是我作死故意让运行时间拖久的
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*执行用时 :1702 ms, 在所有 Java 提交中击败了8.60%的用户
*内存消耗 :45.6 MB, 在所有 Java 提交中击败了100.00%的用户
*2020年6月13日 7:27
*/
class Solution extends SolBase {
public int rand10() {
int num=0;
while(true){
num=343*(rand7()-1)+49*(rand7()-1)+7*(rand7()-1)+rand7()-1;
if(num<10){
return num+1;
}
}
}
}
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*执行用时 :1877 ms, 在所有 Java 提交中击败了8.60%的用户
*内存消耗 :45.3 MB, 在所有 Java 提交中击败了100.00%的用户
*2020年6月13日 7:33
*/
class Solution extends SolBase {
public int rand10() {
int num=0;
while(true){
num=2401*(rand7()-1)+343*(rand7()-1)+49*(rand7()-1)+7*(rand7()-1)+rand7()-1;
if(num<80){
return num%10+1;
}
}
}
}