Figures for 0123456789101112131415… Serialized to a character sequence. In this sequence, bit 5 (counting from subscript 0) is 5, bit 13 is 1, bit 19 is 4, and so on.

Write a function to find any NTH digit. Example 1:

Input: n = 3 Output: 3Copy the code

Example 2:

Input: n = 11 Output: 0Copy the code

Limitations:

0 <= n < 2^31

class Solution {
    public int findNthDigit(int n) {
        // Initializes bits from 1
        int digit = 1;
        // Initialize digit
        long start = 1;
        // Initialize the number of digits
        long count = 9;
        // Determine how many digits n is, and how many digits are left after the start.
        while(n>count){
            n -= count;
            digit += 1;
            start *= 10;
            count = 9 * start * digit;
        }
        // Calculate what the digit corresponding to n should be based on the remaining n-1(excluding the digit starting from start)/digit + start
        long num = start + (n-1) / digit;
        // Convert the number to String and get the subscript of the number n, -'0' because String subscripts start at 0.
        return Long.toString(num).charAt((n - 1) % digit) - '0'; }}Copy the code