【LeetCode 】: 400. 第N个数字

400. 第N个数字

问题描述:

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

请写一个函数,求任意第n位对应的数字。

题目链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/

示例1

输入:n = 3
输出:3

示例2

输入:n = 11
输出:0

完整代码:

class Solution {
    public int findNthDigit(int n) {
        if (n < 0)
            return -1;
        int dig = 1;
        while (true) {
             long count = countOfInt(dig);
             if (n < count * dig) {
                return digAtIndex(n , dig);
             }
             n -= dig * count;
             dig++;
        }
    }

    private long countOfInt(int dig) {
        if (dig == 1)
            return 10;
        return 9 * (long)Math.pow(10 , dig - 1);
    }

    private int digAtIndex(int n , int dig) {
        long num = beginNum(dig) + n / dig;
        long indexFromRight = dig - n % dig;
        for (int i = 1;i < indexFromRight; ++i) {
            num/=10;
        }
        return (int)(num % 10);
    }

    private long beginNum(int dig) {
        if (dig == 1)
            return 0;
        return (long) Math.pow(10 , dig - 1);
    }
}

附加GitHub链接

发布了34 篇原创文章 · 获赞 79 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36008321/article/details/104978892
今日推荐