href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
這是leetcode的第400題--Nth digit
題目
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:
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.
思路 這道題和前面的Integer to Roman 方法類似,要根據n的範圍來劃分不同的結構,這裏就是一個數字的位數,9 , 90 * 2, 900 * 3,... 找到n在的“區間”,然後即找出這個區間的某個數,這個數的某位(digit)
show me the code
class Solution(object): def findNthDigit(self, n): """ :type n: int :rtype: int """ if n <= 9: return n begin = 0 num = 0 while n >= begin: begin = 9 * (10 **num) *(num 1) num = 1 begin -= 9 * (10**(num-1))*num if n == begin : return 9 n -= begin tmp = int((n-1)/ num) 1 int("9"*(num -1)) #floor n = (n-1) % num return int(str(tmp)[n])