题目链接:
https://leetcode-cn.com/problems/implement-rand10-using-rand7/
思路:
首先利用(rand7()-1)*7 随机生成等间隔的数据0,7,14,21,28,35,42
然后利用rand7()在生成数据将数据插入到第一步生成的数据中,保证随机性。
从而得到1,2,3,...,49
对于大于40的数据重新生成,而对于小于的数据对十取模加一,这样保证了1-40之间数据的概率是完全相同的。
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7
class Solution {
public:
int rand10() {
int num;
do
{
num=rand7()+7*(rand7()-1);
}while(num>40);
return num%10+1;
}
};