您的位置:首页 > 其它

leetcode_400. Nth Digit 查找自然数序列中的第n个数字

2016-11-05 17:15 357 查看
题目:

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:
Input:
3

Output:
3


Example 2:
Input:
11

Output:
0

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.


题意:

在自然数的序列1,2,3,4,5,……中,给定数字n,写一个函数,返回这个序列的第n个数字

代码:

class Solution(object):

    def findNthDigit(self, n):

        """

        :type n: int

        :rtype: int

        """

        

        if n > 0 :

            k = 1         #k:记录n对应的数字的位数

            while n > k*9*10**(k-1) :

                n -= k*9*10**(k-1)

                k += 1

            

            

            if n%k == 0 :          #t:记录n为第k位上的第几个数

                t = n/k

            else :

                t = n/k + 1

            

            

            num = 10**(k-1) + t -1         #num:记录n对应的十进制数

            

            temp = n-(t-1)*k             #temp:记录n对应十进制数num上的第几个数字

            

            num_list = []            #将num各个数字分解到num_list中

            while num/10 > 0 :

                num_list.append(num%10)

                num = num/10

            num_list.append(num)

            

            num_list = num_list[::-1]

            

            return num_list[temp-1]         #返回num中的第temp个数字

            

            

笔记:

思路:根据自然数中各个数的数字长度规律,由n推导出n对应自然数序列中的哪个数,以及这个数中的哪个数字,然后将这个数字返回

自然数序列中各个数的数字分布:

1-9:   1*9

10-99: 2*90

100-999:  3*900

个人感觉这个题很无聊,推导过程很繁琐,对应中间变量多,精准度要求很高。

这个题不是我喜欢的类型。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: