题解 | #数字序列中某一位的数字#

数字序列中某一位的数字

http://www.nowcoder.com/practice/29311ff7404d44e0b07077f4201418f5

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param n int整型 
# @return int整型
#
class Solution:
    def findNthDigit(self , n: int) -> int:
        # write code here
        if n == 0:
            return 0
        digit = 1 #数字位数, 1, 2, 3, ...
        start = 1 #起始值, 1, 10, 100
        count = 9 #各个区间的总位数, 9, 9*2*10=180
        while n > count: #1.求n所在的 数字位数区间 如第10位(1)对应数位数区间为2
            n -= count
            digit += 1
            start *= 10
            count = 9 * digit * start #计算不同区间位数的公式
        #2.确定所求位数n对应的数字num
        num = start + (n-1) // digit 
        #3.确定所求位数,确定num对应的位数
        res = int(str(num)[n % digit-1])
        return res
        
            
全部评论

相关推荐

驼瑞驰_招募评论官版...:一共经历几次握手?
点赞 评论 收藏
分享
08-28 20:36
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务