Implement Rand10() Using Rand7() Problem


Description

LeetCode Problem 470.

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().

Example 1:

1
2
Input: n = 1
Output: [2]

Example 2:

1
2
Input: n = 2
Output: [2,8]

Example 3:

1
2
Input: n = 3
Output: [3,8,10]

Constraints:

  • 1 <= n <= 10^5


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
// 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 i,j;
        while ((i = rand7()) > 6);  // P(i is even) = P(i is odd) = 0.5
        while ((j = rand7()) > 5);  // P(j==1) = P(j==2) = P(j==3) = P(j==4) = P(j==5) = 0.2
        return (i&1) ? j : j+5;
    }
};




Related Posts

Beautiful Arrangement II Problem

LeetCode 667. Given two integers n and k, construct a...

Range Addition II Problem

LeetCode 598. You are given an m x n matrix...

Perfect Number Problem

LeetCode 507. A perfect number is a positive integer that...

Optimal Division Problem

LeetCode 553. You are given an integer array nums. The...

Minimum Time Difference Problem

LeetCode 539. Given a list of 24-hour clock time points...

Minimum Moves To Equal Array Elements Problem

LeetCode 453. Given an integer array nums of size n,...