题目描述
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
转自:
作者: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/
题目分析
注意题目中的格式序列,观察可以发现,序列由0,1,2,3,…,n,拼接成字符串而来。
所以,要想求第n位对应的数字,可以从以下分析:
将 101112 ⋯ 中的每一位称为 数位 ,记为 n ;
将 10, 11, 12, ⋯ 称为 数字 ,记为 num;
数字 10 是一个两位数,称此数字的 位数 为 2 ,记为 digit;
每 digit 位数的起始数字(即:1, 10, 100, ,⋯),记为 start 。
根据以上分析,可将求解分为三步:
确定 n 所在 数字 的 位数 ,记为 digit;
确定 n 所在的 数字 ,记为 num;
确定 n 是 num中的哪一数位,并返回结果。
如下图所示,所求数位 在从数字 start 开始的第 [(n - 1) / digit]个 数字 中( start为第 0 个数字)。
num = start + (n - 1) // digit
结论: 所求数位在数字 numnum 中。
代码实现。
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.
}
}
做这类数学问题,一般需要五个变量。
变量digit,代表当前数字位数,例如,10 是一个两位数,称此数字的 位数 为 2 ,记为 digit;
变量start,代表每 digit 位数的起始数字(即:1, 10, 100, ,⋯),记为 start 。
当前位cur,代表个十百千,如1234,4代表个位,3代表百位,记为cur。
高位high,代表当前位的高位,如1234,当前位如果是3,高位是12.记为high。
低位low,代表当前位的低位,如1234,当前位如果是3,低位是4.记为low。