LeetCode – Nth Digit (Java)

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …

For example, given 3, output should be 3. Given 11, output should be 0. (The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, … is a 0, which is part of the number 10)

Java Solution

The solution is obvious when the following is listed.

number range: # of digits in total
1 - 9  : 9
10 - 99 : 90 * 2
100 - 999 : 900 * 3
1000 - 9999 : 9000 * 4
... ... 

For example given n is 1000, we first -9 and then -180. The left is 811. The number is 100+810/3=370. The digit is 0th (810%3). Therefore, the digit is 3.

public int findNthDigit(int m) {
    long n=m; // convert int to long 
    long start=1,  len=1,  count=9;
 
    while(n>len*count){
        n=n-len*count;
        len++;
        count=count*10;
        start=start*10;
    }
 
    // identify the number
    start = start + (n-1)/len;
 
    // identify the digit
    return String.valueOf(start).charAt((int)((n-1)%len))-'0';
}

1 thought on “LeetCode – Nth Digit (Java)”

  1. the explanation is pathetic. Don’t post just for the sake of posting and getting likes. Take some time and pen down your words in a way that it’s simple for the reader to understand.

Leave a Comment