描述:
数字以 0123456789101112131415… 的格式作为一个字符序列,在这个序列中第 2 位(从下标 0 开始计算)是 2 ,第 10 位是 1 ,第 13 位是 1 ,以此类题,请你输出第 n 位对应的数字
解题思路:
1、先找出区间
2、再找到对应位序
3、再提出对应的数字
function findNthDigit( n ) {
// write code here
let count = 1;
let bottom = 0,top = 10
//一直到这个数不比上限大的时候,则跳出循环
while(n>(top-bottom)*count){
//如果数大于这个区间的上限,则不在这个区间,把这个区间里的个数踢出掉
n -= (top-bottom) * count
//以下两步操作是重新规划区间,并让位数+1
count++
bottom = top,top = top*10
}
//n/count为从本区间下限开始的偏移量
//n%count为在该数在区间内对应的下标
//num表示在数字串中第59个数
let num = parseInt(n/count) +bottom;
let r = n%count;
return num.toString()[r]
}
module.exports = {
findNthDigit : findNthDigit
};