# [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]

Note:

rand7 is predefined.
Each testcase has one argument: n, the number of times that rand10 is called.

rand7 返回均匀分布的1到7，要求根据rand7 实现一个rand10, 要求返回均匀分布的1到10。

rand7 -> rand49 -> rand40 -> rand10

## 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() {
const int num = rand40();
return num % 10 + 1;
}
private:
// return 0 ~ 48 randomly
int rand49()
{
return 7 * (rand7() - 1) + rand7() - 1;
}
// return 0 ~ 39 randomly
int rand40()
{
int num = rand49();
while(num >= 40)
{
num = rand49();
}
return num;
}
};
• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

carbon06

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

03-21 875
06-29 35