LeetCode刷题实战470:用 Rand7() 实现 Rand10()
Given the API rand7() that generates a uniform random integer in the range [1, 7], write a function rand10() that generates a uniform random integer in the range [1, 10]. You can only call the API rand7(), and you shouldn't call any other API. Please do not use a language's built-in random API.
Each test case will have one internal argument n, the number of times that your implemented function rand10() will be called while testing. Note that this is not an argument passed to rand10().
示例
示例 1:
输入: 1
输出: [7]
示例 2:
输入: 2
输出: [8,4]
示例 3:
输入: 3
输出: [8,1,10]
解题
class Solution {
public:
int rand10() {
int ans = 0;
do{
ans = (rand7() - 1) * 7 + rand7();
}while(ans > 40);
return ans % 10 + 1;
}
};
LeetCode刷题实战462:最少移动次数使数组元素相等 II