zoukankan      html  css  js  c++  java
  • 470. Implement Rand10() Using Rand7()

    Given the API 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. You can only call the API rand7 and you shouldn't call any other API. Please don't use the system's Math.random().

    Notice that Each test case has one argument n, the number of times that your implemented function rand10 will be called while testing. 

    Follow up:

    1. What is the expected value for the number of calls to rand7() function?
    2. Could you minimize the number of calls to rand7()?

    Example 1:

    Input: n = 1
    Output: [2]
    

    Example 2:

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

    Example 3:

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

    Constraints:

    • 1 <= n <= 105

    keep calling random7() until the result is in the range of [0,1,2,3,4], then return the result

    /**
     * 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() {
            while(true) {
                int r = (rand7() - 1) * 7 + (rand7() - 1);
                if(r < 40) {
                    return r % 10 + 1;
                }
            }
        }
    }
  • 相关阅读:
    生物神经网络和人工神经网络浅谈
    卷积神经网络
    DOM进阶之HTMl属性操作(对象属性)
    01 selenium基本使用补充
    01 selenium基本使用
    day4笔记
    03 获取豆瓣电影top250
    02 爬取视频
    day3笔记
    01 requests基本使用
  • 原文地址:https://www.cnblogs.com/fatttcat/p/13589904.html
Copyright © 2011-2022 走看看