java solution with explanation


  • 0
    Y

    We could split the numbers (<= n) into groups according to the digit count:
    Group 1: 1, 2, ..., 9
    Group 2: 10, 11, ..., 99
    Group 3: 100, 101, ..., 999
    etc.
    Then, with the solution we,
    First, get the group;
    Second, get the number;
    Final, get the digit.

        static public int findNthDigit(int n) {
            int first = 1; // first number of each 'group' (numbers with same length)
            int len = 1;   // length of a number, i.e., digit count of a number
            
            while (n > (long)9 * first * len) { // using 'long' to avoid overflow
                n -= 9 * first * len; // total 9 * first numbers in this 'group'
                first *= 10;
                len++;
            }
            
            int num = first + (n - 1) / len; // the nth digit is in this number
            return (int)(String.valueOf(num).charAt((n - 1) % len)) - '0'; // transfer char to int
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.