给定方法 rand7 可生成 [1,7] 范围内的均匀随机整数,试写一个方法 rand10 生成 [1,10] 范围内的均匀随机整数。
你只能调用 rand7() 且不能调用其他方法。请不要使用系统的 Math.random() 方法。
每个测试用例将有一个内部参数 n,即你实现的函数 rand10() 在测试时将被调用的次数。请注意,这不是传递给 rand10() 的参数。
题目思路:
用范围小的数字表示范围大的数字,思路就是通过计算将范围扩大。因为存在等概率的问题,所以常见的加法、乘法不一定好用。比如说加法表示的话,2 = 1 + 1,但 4 可以 4 = 1 + 3 = 2 + 2,在概率上就增大了。
所以一种思路就是用进制转换表示,这题的思路就是 用两位 7 进制数表示 rand10()。
因为两位 7 进制数 展示最大数据是 6 * pow(7,1) + 6 * pow(7,0) 也就是 0 - 48 之间。最小数 0 不在我们需要的范围之内,所以再主动加 1。比10大的数,全部不要。
package leetcode.pro470;
/**
* The rand7() API is already defined in the parent class SolBase.
* public int rand7();
* @return a random integer in the range 1 to 7
*/
public class Solution2 {
public int rand10() {
int a = rand7();
int b = rand7();
int value = (a - 1) * 7 + (b);
while(value > 10) {
a = rand7();
b = rand7();
value = (a - 1) * 7 + (b);;
}
return value;
}
public int rand7() {
return 1;
}
}