剑指offer刷题笔记-44. 数字序列中某一位的数字

在这里插入图片描述
这题和上个题有点类似,不太难。从1开始,一位数有9个,二位数有90个,三位900个。。。循环把这些个数乘以位数加起来就是在序列中的总位数,直到总位数大于n,这时我们就能知道n所属的数是个几位数。然后找到n输入哪个数和在这个数中所处的位,就能求出n对应的数字
代码如下:

class Solution:
    def findNthDigit(self, n: int) -> int:
        if n == 0: return 0
        digit = 1
        count = 0 #number of characters from 10**0 to 10**digit
        while n > count:
            count += 9*digit*10**(digit-1)
            digit += 1
        digit -= 1
        count -= 9*digit*10**(digit-1)
         
        num = 10**(digit-1) + int((n-count-1)/digit) # the number nth element belong to
        ind = (n-count-1) % digit # the index of n in num, 0 for the highest digit
        return int(num/(10**(digit-1-ind))) - int(num/(10**(digit-ind))) * 10

第一次时间100,纪念一下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值