From c452b005b5f344dd4e344b531f098f962e46a464 Mon Sep 17 00:00:00 2001 From: CyC2018 Date: Fri, 30 Oct 2026 20:18:04 +0800 Subject: [PATCH] =?UTF-8?q?Update=2044.=20=E6=95=B0=E5=AD=97=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E4=B8=AD=E7=9A=84=E6=9F=90=E4=B8=80=E4=BD=8D=E6=95=B0?= =?UTF-8?q?=E5=AD=97.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 补充 Leetcode 链接与题目计数说明;补充解题思路及推导示例,并将代码中统计位数的变量类型调整为 long。 --- notes/44. 数字序列中的某一位数字.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/notes/44. 数字序列中的某一位数字.md b/notes/44. 数字序列中的某一位数字.md index 3d869f3a..7ac75d24 100644 --- a/notes/44. 数字序列中的某一位数字.md +++ b/notes/44. 数字序列中的某一位数字.md @@ -1,19 +1,27 @@ # 44. 数字序列中的某一位数字 +[Leetcode](https://leetcode.cn/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/) + ## 题目描述 -数字以 0123456789101112131415... 的格式序列化到一个字符串中,求这个字符串的第 index 位。 +数字以 0123456789101112131415... 的格式序列化到一个字符串中,求这个字符串的第 index 位(从 0 开始计数)。力扣的版本序列从 1 开始、k 从 1 开始计数,结果与本题相同,把函数名改为 findKthNumber 即可。 ## 解题思路 +先确定第 index 位落在几位数里:0~9 共 10 个数,占 10 位;10~99 共 90 个两位数,占 180 位;100~999 占 2700 位……依次减去各段的长度,直到 index 落在某一段内。再用 index / place 算出它是这一段的第几个数,index % place 是这个数的第几位。 + +例如 index = 1000:减去 10 和 180 后剩 810,落在三位数段;810 / 3 = 270,对应 100 + 270 = 370;810 % 3 = 0,取 370 的第 0 位,结果为 3。 + +需要注意的是 index 接近 231 时会进入九位数段,这一段的长度 9 × 108 × 9 超出 int 的范围,因此 totalAmount 用 long。 + ```java public int getDigitAtIndex(int index) { if (index < 0) return -1; - int place = 1; // 1 表示个位,2 表示 十位... + int place = 1; // 1 表示一位数,2 表示两位数... while (true) { int amount = getAmountOfPlace(place); - int totalAmount = amount * place; + long totalAmount = (long) amount * place; if (index < totalAmount) return getDigitAtIndex(index, place); index -= totalAmount;