剑指 Offer 44. 数字序列中某一位的数字
题目描述
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
思路:
n - 1,除掉首位的0,一位的有9个,两位的有90个。。。以此类推。cnt 用于存储这些,cnt x digit 表示这些数占用的位置数,
比如 897,n最后把前面的0到99都踢掉了,起始位置为100,digit为3,然后定位,得到最终答案。
class Solution:
def findNthDigit(self, n: int) -> int:
n -= 1
cnt, digit = 9, 1
while n > cnt * digit:
n -= cnt * digit
digit += 1
cnt *= 10
ind = n // digit
loc = n % digit
num = 10 ** (digit - 1) + ind
return int(str(num)[loc])