400. Nth Digit
problem
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.
渣英语开始没看懂题目
大意是讲自然序列的正整数视为一个包含0-9的字符串,求其中第n个0-9具体是什么
solution
生成一个长字符串,查出N (容易Memory Limit Exceeded )
或者根据规律算出N
难点在于数字n其实有两个属性,一个是变化为字符串的属性,一个是自己数字的属性,如果混淆很难理解
规律如下,分为如下几段
1-9:包含字符数字个数 9,每个字符数字长度1;
10-99:包含字符数字个数90,每个字符数字长度2;
以此类推
- 根据上面规律,首先判断数字n位于字符数字哪一段中
- 每一轮循环n的数字都是减去上一段字符数字个数,可以理解为n的起始位置变更为每段的开始(n变小,n开始的位置也变化,n指向位置不变)
- 当n小于段长时,表明已经获取到n在哪一段中
- 在此段中求取n的位置
- 已知段开始值difit,每个字符数字的字符长度charSize, difit + (n-1) / charSize即为n所在的字符数字,[n % charSize-1]即为在字符数字中的具体下标
- 为什么‘-1’(第一个)?以11为例(n=2),如果不-1,则n所在的字符数字为,10+2/2 = ‘11’, 其实此时数字11位于字符数字‘10’
; - 第二个-1:同样11为例,如果不-1,此时下标为2%2 == 0, 10[0]= '1' ;刚好整除的时候,数字实际刚好位于字符数字最后一位,下标应为2%2-1
class Solution(object):
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
charSize = 1
numSize = 9
difit = 1
while n > charSize * numSize:
n -= charSize * numSize
charSize += 1
difit *= 10
numSize = 9 * difit
#print 'n,difit,charSize',n,difit,charSize
#print 'str', str(difit + (n-1)/ charSize)
#print '[]',[n % charSize-1]
return int(str(difit + (n-1) / charSize)[n % charSize-1])

浙公网安备 33010602011771号