From a214636854bdbaf698761b8193493a932ca19200 Mon Sep 17 00:00:00 2001 From: CyC2018 Date: Sun, 25 Oct 2026 21:34:16 +0800 Subject: [PATCH] =?UTF-8?q?Update=20Leetcode=20=E9=A2=98=E8=A7=A3=20-=20?= =?UTF-8?q?=E6=95=B0=E5=AD=A6.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充用 Rand7() 实现 Rand10()。 --- notes/Leetcode 题解 - 数学.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/notes/Leetcode 题解 - 数学.md b/notes/Leetcode 题解 - 数学.md index 8060fbea..05da7be7 100644 --- a/notes/Leetcode 题解 - 数学.md +++ b/notes/Leetcode 题解 - 数学.md @@ -25,6 +25,7 @@ * [2. 3 的 n 次方](#2-3-的-n-次方) * [3. 乘积数组](#3-乘积数组) * [4. 找出数组中的乘积最大的三个数](#4-找出数组中的乘积最大的三个数) + * [5. 用 Rand7() 实现 Rand10()](#5-用-rand7-实现-rand10) @@ -533,3 +534,24 @@ public int maximumProduct(int[] nums) { return Math.max(max1*max2*max3, max1*min1*min2); } ``` + +### 5. 用 Rand7() 实现 Rand10() + +470\. Implement Rand10() Using Rand7() (Medium) + +[Leetcode](https://leetcode.com/problems/implement-rand10-using-rand7/) / [力扣](https://leetcode.cn/problems/implement-rand10-using-rand7/) + +题目描述:已知 rand7() 等概率返回 1 \~ 7,只用它实现等概率返回 1 \~ 10 的 rand10()。 + +把两次 rand7() 的结果看成一个两位的 7 进制数,(rand7() - 1) * 7 + rand7() 能等概率地生成 1 \~ 49。只保留 1 \~ 40,它们对 10 取余之后 0 \~ 9 各出现 4 次,仍然是等概率的;落在 41 \~ 49 时重新生成,这种方法称为拒绝采样。 + +```java +public int rand10() { + while (true) { + int x = (rand7() - 1) * 7 + rand7(); + if (x <= 40) { + return (x - 1) % 10 + 1; + } + } +} +```