leetcode【400】Nth Digit(python)
阿新 • • 發佈:2018-11-13
寫在最前面:
為什麼我覺得這道簡單的題好難啊...感覺自己是個數學渣渣
純原創,不會有人和我一樣奇葩的思路的...
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 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.
求出幾位數
在這個幾位數的第幾個
屬於哪個數字
屬於哪一個數字的第幾個字元
自己領悟吧~
class Solution: def findNthDigit(self, n): """ :type n: int :rtype: int """ digit = 1 while n > digit*9*10**(digit-1): n -= digit*9*10**(digit-1) digit += 1 a = n // digit b = n % digit if a == 0: c = 10 ** (digit-1) + a else: c = 10 ** (digit-1) + a -1 if b == 0: return int(str(c)[digit-1]) else: return int((str(c+1)[b-1]))