****LeetCode400. Nth Digit

本文介绍了一种算法,用于找到无限整数序列1,2,3,4,...中的第N位数字,通过计算start、size、step等变量,有效定位目标数字并返回其值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

思路:这道题的意思是把所有数字排列12345678910111213...,然后返回第n位的数字.

class Solution(object):
    def findNthDigit(self, n):
        """
        :type n: int
        :rtype: int
        """
        start = 1
        size = 1
        step = 9
        
        while (n>size*step):
            n = n - size*step
            step = step * 10
            start = start * 10
            size = size + 1
        num = str((n-1)/size + start)
        return int(num[(n-1)%size])

比如输入n=4590,那经过运算输出的结果n: 1701, step: 9000, start: 1000, size: 4, num: 1425    return:1

size表示现在计算的是4位数

start就是4位数的开始数字(1000)

step计算的是进入下一循环需要跨过多少数字.(4位数start是1000,5位数start是(1000+9000)=10000)

n是指'123456789101112...998999'这个字符串到数字999已经经过了(4590-1710)=2880位,接下来要计算的是从'100010011002...14241425...'中的1710位

num指的是第4590位数字1425中的某一个数字

最后的(n-1)%size确定的是数字1425中的第几位数.计算结果为0,所以是'1425'的第一位,最终返回1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值