問題描述: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')