LeetCode 470. Implement Rand10() Using Rand7()

题目描述

Given a function rand7 which generates a uniform random integer in the range 1 to 7, write a function rand10 which generates a uniform random integer in the range 1 to 10.
Do NOT use system's Math.random().

Example 1:

Input: 1
Output: [7]

Example 2:

Input: 2
Output: [8,4]

Example 3:

Input: 3
Output: [8,1,10]

题目思路

代码 C++

  • 思路一、
// 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 result = 7 * (rand7() - 1) + rand7();
        while(result > 40){
            result = 7 * (rand7() - 1) + rand7();
        }
        return result%10 + 1;
    }
};

总结展望

  • 已知random7求random10

你可能感兴趣的:(LeetCode 470. Implement Rand10() Using Rand7())