https://leetcode-cn.com/problems/implement-rand10-using-rand7/
思路:
1. [1,7] 的随机数, 减一-> [0,6] 的随机数,乘以7 -> {0,7,14,21,28,35,42} 中的随机数
2. [1,7]的随机数
1+2 是[1,49]的随机数,且均匀生成 -> [0,48]的随机数
取出[0,39]区间 取到的概率是1/49 除以4-> [0,9]的随机数 加一->[1,10]的随机数
代码:
class Solution {
public:
int rand10() {
while(1){
int rand49 = (rand7()-1)*7+rand7()-1;
if(rand49<=39){
return rand49/4+1;
}
}
return 0;
}
};