当前位置:网站首页>[Jianzhi offer] interview question 44 A digit in a sequence of numbers

[Jianzhi offer] interview question 44 A digit in a sequence of numbers

2022-06-22 21:02:00 LuZhouShiLi

Interview questions 44. A digit in a sequence of numbers

subject

The numbers are in 0123456789101112131415… Serializes the format of a string into a sequence of characters . In this sequence , The first 5 position ( From the subscript 0 Start counting ) yes 5, The first 13 Is it 1, The first 19 Is it 4, wait .
Please write a function , Ask for any n The number corresponding to bit

Ideas

Looking for a regular , Thank you very much

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/

Code

class Solution {
    
    public int findNthDigit(int n) {
    
        int digit  = 1;
        long start = 1;
        long count = 9;

        while(n > count)
        {
    
            n -= count;
            digit += 1;
            start *= 10;
            count  = digit * start * 9;
        }

        //  determine n The number in which 
        long num = start + (n - 1) / digit; 
        //  determine N  stay num Which digit of 
        return Long.toString(num).charAt((n - 1) % digit) - '0';
    }
}

原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221929038305.html