当前位置:网站首页>470. Rand10() is implemented with rand7()

470. Rand10() is implemented with rand7()

2022-04-23 17:32:00 hequnwang10

One 、 Title Description

Given method rand7 Generative [1,7] Uniform random integer in range , Try to write a method rand10 Generate [1,10] Uniform random integer in range .

You can only call rand7() And you can't call other methods . Please do not use the system's Math.random() Method .

Each test case will have an internal parameter n, That is, the function you implement rand10() The number of times it will be called during the test . Please note that , This is not passed on to rand10() Parameters of .

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

Two 、 Problem solving

Reject sampling

 Insert picture description here

/** * The rand7() API is already defined in the parent class SolBase. * public int rand7(); * @return a random integer in the range 1 to 7 */
class Solution extends SolBase {
    
    public int rand10() {
    
        int maxNum = Integer.MAX_VALUE;
        while(maxNum > 40){
    
            maxNum = rand7() + (rand7()-1) * 7;
        }
        return 1+maxNum%10;
    }
}

版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231732009467.html