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.
Analysis
1位数有 1- 9, 共9个, 占9位
2位数有 10-99, 共90个, 占 90x2=180位
3位数有 100-999,共900个, 占900x3=2700位
。。。
比如第149个数,发现149>9, 所以149-9 = 140
140<180,所以No.149在二位数。
140/2 = 70 ,所以是第70个二位数。 即 70+9 = 79
140%2==0, 所以是79的第二位数,即9
所以答案是9
Code(Python)
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
base = 9 # base number
digit = 1 # the number of bit
pre = 1 # the previor number
while n > base*digit:
pre += base
n -= base*digit
digit += 1
base *= 10
return int(str((n-1)/digit + pre)[(n-1)%digit])