面试题44.数字序列中的某一位数字
题目
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字
思路
找规律,真的会谢
https://leetcode.cn/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/
代码
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;
}
// 确定n所在的数字
long num = start + (n - 1) / digit;
// 确定N 在num的哪一个数位
return Long.toString(num).charAt((n - 1) % digit) - '0';
}
}