1.题目描述
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例1:
输入:n = 3 输出:3
示例2:
输入:n = 11 输出:0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
2.思路分析
- 将 101112⋯ 中的每一位称为 数位 ,记为 n ;
- 将 10, 11, 12,⋯ 称为 数字 ,记为 num ;
- 数字 10是一个两位数,称此数字的 位数 为 2,记为 digit;
- 每 digit 位数的起始数字(即:1, 10, 100,⋯),记为 start 。
观察上表,可推出各 digit下的数位数量 count 的计算公式:
count=9×start×digit
根据以上分析,可将求解分为三步:
- 确定 n 所在 数字 的 位数 ,记为 digit ;
- 确定 n 所在的 数字 ,记为 num ;
- 确定 n 是 num 中的哪一数位,并返回结果。
3.解答
class Solution {
//找规律 + 迭代
public int findNthDigit(int n) {
int digit = 1;
long start = 1;
long count = 9;
while (n > count) { // 1.
n -= count;
digit += 1;
start *= 10;
count = digit * start * 9;
}
long num = start + (n - 1) / digit; // 2.
return Long.toString(num).charAt((n - 1) % digit) - '0'; // 3.
}
}
- 时间复杂度 O(log n)
- 空间复杂度 O(log n)
详细分析请阅读: https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/mian-shi-ti-44-shu-zi-xu-lie-zhong-mou-yi-wei-de-6/