美文网首页
LeetCode 470. Implement Rand10()

LeetCode 470. Implement Rand10()

作者: cb_guo | 来源:发表于2019-03-24 15:56 被阅读0次

题目描述

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;
    }
};

总结展望

相关文章

网友评论

      本文标题:LeetCode 470. Implement Rand10()

      本文链接:https://www.haomeiwen.com/subject/ntpuvqtx.html