Skip to the content.

44. 数字序列中某一位的数字

数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。 请写一个函数,求任意第n位对应的数字。

示例 1:

输入:n = 3
输出:3

示例 2:

输入:n = 11
输出:0

限制:

0 <= n < 2^31

注意:本题与主站 400 题相同:https://leetcode-cn.com/problems/nth-digit/

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路和方法:

本题就越是找数学规律,从下面列表可以得出: 数值位数 = start(范围开始值) * 9 * digit(位数 - 1)。

    数字范围    数量  位数    占多少位
    1-9        9      1       9         => 1 * 9 * (10 ** 0)
    10-99      90     2       180       => 2 * 9 * (10 ** 1)
    100-999    900    3       2700      => 3 * 9 * (10 ** 2)
    1000-9999  9000   4       36000     => 4 * 9 * (10 ** 3)
    ...                                 => n * 9 * (10 ** (n - 1))
function findNthDigit(n: number): number {
    let digit: number = 1 // 位数
    let start: number = 1 // 所在范围开始值
    let count: number = 9 // 已计算占位数
    while(n > count) {
        n -= count
        digit++
        start *= 10
        count = digit * start * 9
    }
    let theNumber: number = start + (n - 1) / digit // 计算n对应的数字
    return parseInt(theNumber.toString()[(n - 1) % digit]) // 找出在数字中对应的位置
};

leetcode题解精选

作者:jyd 链接:https://leetcode.cn/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/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 ```

解题总结

这道题主要考察map的用法,只要想到能够使用map使用,不会很难。