C++ | Leetcode C++题解之第470题用Rand7()实现Rand10()
题目:
题解:
class Solution {
public:
int rand10() {
int a, b, idx;
while (true) {
a = rand7();
b = rand7();
idx = b + (a - 1) * 7;
if (idx <= 40) {
return 1 + (idx - 1) % 10;
}
a = idx - 40;
b = rand7();
// get uniform dist from 1 - 63
idx = b + (a - 1) * 7;
if (idx <= 60) {
return 1 + (idx - 1) % 10;
}
a = idx - 60;
b = rand7();
// get uniform dist from 1 - 21
idx = b + (a - 1) * 7;
if (idx <= 20) {
return 1 + (idx - 1) % 10;
}
}
}
};
原文地址:https://blog.csdn.net/Ddddddd_158/article/details/142836663
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!