问题描述:git
在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 个数字。app
注意:
n 是正数且在32为整形范围内 ( n < 231)。spa
示例 1:code
输入: 3 输出: 3
示例 2:blog
输入: 11 输出: 0 说明: 第11个数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是0,它是10的一部分。
方法(times out):it
1 class Solution(object): 2 def findNthDigit(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 if n < 10: 8 return n 9 lis = [0,1,2,3,4,5,6,7,8,9] 10 11 for i in range(10,n+1): 12 templist = [] 13 while i != 0: 14 temp = i % 10 15 i = i // 10 16 templist.append(temp) 17 templist.reverse() 18 for i in templist: 19 lis.append(i) 20 return lis[n]
官方:io
1-9 9 * 1 = 9个class
10-99 90 * 2 = 180个object
100-999 900 * 3 = 270个方法
设 digit表明几位数1,2,3,base表明每位数的个数9,90,900,ith表明该数的起始位置10,100,1000
设 n = 12
首先判断12在
1 class Solution(object): 2 def findNthDigit(self, n): 3 """ 4 :type n: int 5 :rtype: int 6 """ 7 digit = 1 8 base = 9 9 ith = 1 10 while n > digit * base: 11 n -= digit * base 12 ith += base 13 digit += 1 14 base = 10*base 15 return ord(str((n-1)//digit + ith)[(n-1)%digit]) - ord('0')