Nth Digit

The problem asks to return the nth digit of an infinite integer sequence starting from 1.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def findNthDigit(self, n: int) -> int:
        # Start with digits of length 1
        length = 1
        count = 9

        # Reduce n by the total count of digits in numbers with the current length
        while n > length * count:
            n -= length * count
            length += 1
            count *= 10

        # Determine the actual number where the nth digit is
        start = 10 ** (length - 1)
        number = start + (n - 1) // length

        # Return the specific digit within that number
        return int(str(number)[(n - 1) % length])

Explanation:

  1. Determine the Length of the Number: The code first determines the length of the number containing the nth digit by subtracting the total count of digits in numbers of each length (e.g., there are 9 single-digit numbers, 90 two-digit numbers, 900 three-digit numbers, etc.).

  2. Find the Specific Number: Once the correct length is found, the code calculates the actual number that contains the nth digit.

  3. Extract the Specific Digit: Finally, the code extracts and returns the specific digit within that number.