,在无限的整数序列(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...)中查找第n个数字
注意:n是正数,且n<2^31
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
1:本题是一道数字规律题
我们先总结一下整数中数字的规律
个位数整数范围:1-9,整数数量为9,每个整数包含的数字为1,总数字为9
十位数整数范围:10-99,整数数量为90,每个整数包含的数字为2,总数字为180
百位数整数范围:100-999,整数数量为900,每个整数包含的数字为3,总数字为2700
千位数整数范围:1000-9999,整数数量为9000,每个整数包含的数字为4,总数字为36000
万位数整数范围:10000-99999,整数数量为90000,每个整数包含的数字为5,总数字为450000
从上可知,随位数的增加(从个位到万位),整数数量以10的倍数增加,每个整数包含的数字以1累加
def findNthDigit(self, n):
"""
:type n: int
:rtype: int
"""
if n < 10: #个位数
return n
n -= 9 #减个位数总数9
numSum = 90 #个位数整数个数为9,十位数整数个数为90,百位数为900
diPerInt = 2 #每个整数中包含数字的个数,1-9为1,10-99为2,100-999为3
while True:
if n <= numSum * diPerInt: #属于某个位数范围
rest = n % diPerInt #余数
n = n // diPerInt - 1 #该范围中第n个数
curDigit = numSum // 9 + n #从当前位数开始的整数
if rest == 0: #余数为零
return int(str(curDigit)[-1])
else: #余数不为零
curDigit += 1 #当前数累加1
return int(str(curDigit)[rest - 1])
else: #超过某个位数范围
n -= numSum * diPerInt #减去该位数范围
diPerInt += 1 #整数的数字个数加1,如10(2)变为100(3)
numSum *= 10 #位数加1,如从十位数到百位数
算法题来自:https://leetcode-cn.com/problems/nth-digit/description/