LeetCode 400: Nth Digit
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …
Example:
Input: n = 11
Output: 0
Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, … is 0
, which is part of the number 10.
n
?
1 <= n <= 2*10^9
n
th digit falls. The sequence of digits can be broken down into segments based on number length:
n
th digit.n
th digit is located.def findNthDigit(n: int) -> int:
# Initialize the length of digits we are looking at and the count of numbers
length = 1
count = 9
start = 1
# While n is greater than the digits in the current range, narrow down the range
while n > length * count:
n -= length * count
length += 1
count *= 10
start *= 10
# Now n is within the current range denoted by length
# Find the exact number where the nth digit is located
start += (n - 1) // length
# Find the exact digit within the number
s = str(start)
digit_index = (n - 1) % length
return int(s[digit_index])
# Example Usage:
n = 11
print(findNthDigit(n)) # Output: 0
while
loop runs logarithmically by increasing the length
and adjusting count
by powers of 10.This code efficiently narrows down the exact range and finds the specific digit in the continuous sequence of integers.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?