剑指 Offer 44. 数字序列中某一位的数字

题目描述

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

示例 1:
输入:n = 3
输出:3

解题思路
代码
class Solution {
    public int findNthDigit(int n) {
        int len = 1, i = 1;
        long range = 9;
        while(n > len * range){
            n -= len * range;
            len++;
            range *= 10;
            i *= 10;
        }
        i += (n - 1) /len;
        String s = Integer.toString(i);
        return Character.getNumericValue(s.charAt((n - 1) % len));
    }
}

参考:https://leetcode.com/problems/nth-digit/discuss/88363/Java-solution
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/

猜你喜欢

转载自blog.csdn.net/LiuXiaoXueer/article/details/107928724