https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
限制:
0 <= n < 2^31
注意:本题与主站 400 题相同:https://leetcode-cn.com/problems/nth-digit/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
先判断每个区间的字符个数,找到对应的区间你,然后在找
执行用时: 28 ms , 在所有 Python3 提交中击败了 98.74% 的用户 内存消耗: 14.9 MB , 在所有 Python3 提交中击败了 47.03% 的用户
class Solution:
def findNthDigit(self, n: int) -> int:
if(n==0):
return 0
n-=1
digits=1 #每个数字的字符数
starts=1 #区间开始的下标数
counts=digits*starts*9 #区间内的个数
while(n>counts):
n-=counts
digits+=1
starts*=10
counts=digits*starts*9
#跳出循环
number=starts+n//digits
res=str(number)[n%digits]
return int(res)