题目
- 数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从0开始计数)是5,第13位是1,第19位是4,等等。请写一个函数,求任意第n位对应的数字。
- leetcode链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/
思路
正确的思路是找出某些规律跳过若干数字。例如:序列前十位是0-9。接下来180位数字是90个10-99的两位数。接下来的2700位是900个100~999的三位数。
代码
/**
* @param {number} n
* @return {number}
*/
var findNthDigit = function(n) {
if (n <= 9) return n
let digit = 1
let counts = 9
while (n > counts) {
n -= counts
digit++
counts = digit * 9 * Math.pow(10, digit - 1)
}
const start = Math.pow(10, digit - 1)
const prevCounts = Math.floor(n / digit)
const isCurrent = n % digit === 0
const num = isCurrent ? `${start + prevCounts - 1}` : `${start + prevCounts}`
return isCurrent ? num[num.length - 1] : num[(n % digit) - 1]
};