1. 题目描述
数字以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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 题解
规律:
根据题目,我们的任务就是由 数位数量 推得 该位数字:
- 首先用循环让n不断的减去count就可以得到在对应数字范围内该数字所在的位数(以start为0开始数的),如 n = 15时,n-9得6,6表明结果是10-99范围内的第6位数字;
- 然后得到该位数字所在的 num,也就是12,num = start + (n-1)/digit ;
- 最后判断是num中的哪一位即可,即 (n-1)%digit 位。
/**
* @param {number} n
* @return {number}
*/
var findNthDigit = function(n) {
let start = 1;
let digit = 1;
let count = 9;
while(n > count){ //1.
n = n - count;
digit += 1;
start *= 10;
count = 9 * start * digit;
}
let num = start + (n-1)/digit; //2.
let str = num.toString();
return str.charAt((n-1)%digit) - 0; //3.
};
参考: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/