题目
思路
转二进制实现
代码
下面展示一些 具体代码
。
// A code block
var foo = 'bar';
// An highlighted block
/**
* 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 num =0;
do{
num = ((rand2()<<3)+(rand2()<<2)+(rand2()<<1)+rand2());
}while(num>9);
return num+1;
}
public int rand2(){
int rand = 0;
do{
rand = rand7();
}while(rand==7);
//1-3 0
if(rand<4){
return 0;
}else{//4-6 1
return 1;
}
}
}
运行结果
题目连接
https://leetcode-cn.com/problems/implement-rand10-using-rand7/