470. 用 Rand7() 实现 Rand10()
挺有趣的
先把代码放上来,明天重新推一遍理论再放上来
class Solution {
public:
int rand10() {
while(true) {
int a = rand7(), b = rand7();
int res = (a - 1) * 7 + b;
if (res <= 40) return res % 10 + 1;
a = res - 40, b = rand7();
res = (a - 1) * 7 + b;
if (res <= 60) return res % 10 + 1;
a = res - 60, b = rand7();
res = (a - 1) * 7 + b;
if (res <= 20) return res % 10 + 1;
}
}
};