数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
限制:
0 <= n < 2^31
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
思路
将 101112中的每一位称为 数位 ,记为 n;
将 10, 11, 12, ⋯ 称为 数字 ,记为 num;
数字 10 是一个两位数,称此数字的 位数 为 2 ,记为 digit ;
每 digit位数的起始数字(即:1, 10, 100,⋯),记为 start 。
找规律,得出相关联系。
1、由表格可知道每一个位数对应的数位,通过不断减去数位,得出n所在的位数以及数字范围;
2、由start + (n-1)/digit得出n所属于哪个数字(比如数位n=15时候,属于数字12)
3、由(n−1)%digit得出n所属的数字的具体位置(比如数字12中的1)
作者:jyd
链接: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/
来源:力扣(LeetCode)
代码
class Solution {
public int findNthDigit(int n) {
int digit = 1;
long start = 1;
long count = 9;
while(n > count){
n -= count;
digit += 1;
start *= 10;
count = digit * start * 9;
}
long num = start + (n-1)/digit;
return Long.toString(num).charAt((n-1)%digit)-'0';
}
}