# Short Python+Java

• Check the same-length ranges 1-9, 10-99, 100-999, 1000-9999, etc.

Python:

``````def findNthDigit(self, n):
n -= 1
for digits in range(1, 11):
first = 10**(digits - 1)
if n < 9 * first * digits:
return int(str(first + n/digits)[n%digits])
n -= 9 * first * digits
``````

Java:

``````public int findNthDigit(int n) {
n -= 1;
int digits = 1, first = 1;
while (n / 9 / first / digits >= 1) {
n -= 9 * first * digits;
digits++;
first *= 10;
}
return (first + n/digits + "").charAt(n%digits) - '0';
}
``````

Using divisions instead of multiplications to prevent overflow.

• Hey Stefan, would you mind explaining your solution? Thanks

• @lekzeey I more or less wrote the same program. Assume 99<n<999.
First (bad ) idea: You can make a string concatenating consecutive numbers until your string has len n and find the entry on that position, but this is not a good approach.
Second idea: Note that numbers from 0 to 9 have one digit, numbers from 10 to 99 have two digits, numbers from 100 to 999 have 3 digits and so on. If you know that 99<n<999 then you can consider instead n-99 and then make a string concatenating consecutive numbers starting from 100 until your string has length n-99.
Third idea: We begin like in the second idea, but we don't make any string! Since numbers 99<x<999 have the same length, it is easier to calculate the n-99th digit directly.
Hope this helps.

• @lekzeey
str(first + n/digits) => the string of the number
n%digits => the digit position in this string

It's very tricky for n -= 1 at the beginning.

• impressive !!!

• beautiful variable naming

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