这题和上个题有点类似,不太难。从1开始,一位数有9个,二位数有90个,三位900个。。。循环把这些个数乘以位数加起来就是在序列中的总位数,直到总位数大于n,这时我们就能知道n所属的数是个几位数。然后找到n输入哪个数和在这个数中所处的位,就能求出n对应的数字
代码如下:
class Solution:
def findNthDigit(self, n: int) -> int:
if n == 0: return 0
digit = 1
count = 0 #number of characters from 10**0 to 10**digit
while n > count:
count += 9*digit*10**(digit-1)
digit += 1
digit -= 1
count -= 9*digit*10**(digit-1)
num = 10**(digit-1) + int((n-count-1)/digit) # the number nth element belong to
ind = (n-count-1) % digit # the index of n in num, 0 for the highest digit
return int(num/(10**(digit-1-ind))) - int(num/(10**(digit-ind))) * 10
第一次时间100,纪念一下: