470. Implement Rand10() Using Rand7()
参考花花酱的视频讲的很清楚。
/**
* 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 index = Integer.MAX_VALUE;
while (index >= 40) { // work for 0-39
index = 7 * (rand7() - 1) + (rand7() - 1);
}
return index % 10 + 1;
}
}