Update 44. 数字序列中的某一位数字.md

补充 Leetcode 链接与题目计数说明;补充解题思路及推导示例,并将代码中统计位数的变量类型调整为 long。
This commit is contained in:
CyC2018
2026-10-30 20:18:04 +08:00
parent c3a9c3a38b
commit c452b005b5
+11 -3
View File
@@ -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 接近 2<sup>31</sup> 时会进入九位数段,这一段的长度 9 × 10<sup>8</sup> × 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;