《剑指Offer》刷题笔记——面试题44. 数字序列中某一位的数字

难度:中等

一、题目描述:

在这里插入图片描述

二、解题分析:

1、leetcode解析

在这里插入图片描述

2、代码实现

# 规律:1-9有9个数,10-99有20*9个数字,100-999有300*9个数字,1000-9999有4000*9个数字
class Solution(object):

    def findNthDigit(self, nth: int) -> int:
        # 所在位数规律:9 * pow(10, i - 1) * i
        i, max_count = 0, 0
        while max_count < nth:
            i += 1
            max_count += i * (9 * 10 ** (i - 1))

        # 起始值对应的次数(nth)
        start_count = max_count - i * (9 * 10 ** (i - 1))

        power = i - 1  # 幂(用于求所在位数)
        start_val = 10 ** power  # 起始值

        step = nth - start_count - 1  # 剩余移动步数
        step_length = i  # 每增一需要的步长
        # offset - 偏移值(从起始值开始)
        # pos - 结果值指向的位数 - 从最高位开始偏移
        offset, pos = divmod(step, step_length)

        curr_val = start_val + offset  # 当前数值 - 起始值 + 偏移值
        # 对应位数的数字,即解
        result = curr_val // 10 ** (power - pos) % 10

        return result
发布了132 篇原创文章 · 获赞 154 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_34108714/article/details/104732950