问题描述
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
问题解决
class Solution {
public int findNthDigit(int n) {
//初始化
int digit = 1;
long count = 9, start = 1;
while(count < n) {
n -= count;
digit++;
start *= 10;
count = 9 * start * digit;
}
long num = start + (n - 1) / digit;
String str = String.valueOf(num);
int res = str.charAt((n-1) % digit) - '0';
return res;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。