[LeetCode] Implement Rand10() Using Rand7()

470. Implement Rand10() Using Rand7()

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
2
3
4
5
6
7
8
9
10
11
12
// The rand7() API is already defined for you.
// int rand7();
// @return a random integer in the range 1 to 7

class Solution {
public:
int rand10() {
int res = 0;
for(int i = 0; i < 10; i++) res += rand7();
return res % 10 + 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/29/PS/LeetCode/implement-rand10-using-rand7/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.