剑指 Offer 44. 数字序列中某一位的数字20201007

    科技2024-05-31  89

    数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。

    请写一个函数,求任意第n位对应的数字。

    链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof

    找规律很重要! 思路: 1.首先确定第n位数字对应整数的位数,比如说第11位,它对应的数字是10,有两位,有规律如下: 0-9有10个数字,他们是1位 10-99有9x10个数字,他们是2位 100-999有9x102个数字,他们是3位 … 因为n<231, 那么只用取到109,用一个列表来存,并来比较

    list_stand_temp = [10]+[i*9*10**(i-1) for i in range(2, 10)] list_stand =[sum(list_stand_temp[:i]) for i in range(1, 10)] temp = 0 # temp+1 表示在n位置上的数按照数字来说是几位数 if n < 10: return n while True: if n >= list_stand[temp]: temp += 1 else: temp_n = n - list_stand[temp-1] break

    2.计算第n位对应的数字和应该取该数字的第几位 temp_n是在第n位对应的是temp+1位数字的temp_n位,比如第12位对应的是2位数字的第2位,第15位对应的是2位数字的第5位,那么因为temp_n是第temp+1位数字中的,那么temp_n // (temp+1)就对应的是偏移量,而起点是10temp,number计算的就是第n位对应的数字,index_number就是计算在这个数字内的偏移量

    (index_number, index_digit) = divmod(temp_n, temp+1) number = 10 ** temp + index_number return int(str(number)[index_digit])

    总体代码如下:

    class Solution: def findNthDigit(self, n: int) -> int: list_stand_temp = [10]+[i*9*10**(i-1) for i in range(2, 10)] list_stand =[sum(list_stand_temp[:i]) for i in range(1, 10)] temp = 0 # temp+1 表示在n位置上的数按照数字来说是几位数 if n < 10: return n while True: if n >= list_stand[temp]: temp += 1 else: temp_n = n - list_stand[temp-1] break (index_number, index_digit) = divmod(temp_n, temp+1) number = 10 ** temp + index_number return int(str(number)[index_digit])
    Processed: 0.013, SQL: 8