题目
思路
- 多个rand()组成n进制的情况,如rand()可得到7*7=49个值,然后舍弃其中9个,得到结果。
- 以rand7()取6个,另一个取5个,取6个的判断奇偶,两种情况;取5个的,五种情况。则2*5=10种情况。
- 利用c++的random库提供的API
实现
class Solution {
public:
int rand10() {
int index;
do{
int first = rand7();
int second = rand7();
index = (first - 1) * 7 + second;
}while(index > 40);
return 1 + (index - 1) % 10;
}
};
class Solution {
public:
int rand10() {
int a, b;
while((a = rand7()) == 7);
while((b = rand7()) > 5);
return a & 1 ? 5 + b : b;
}
};
std::default_random_engine random{ time(NULL) };
std::uniform_int_distribution dis1{ 1, 7 };
int rand7() {
return dis1(random);
}