LeetCode 剑指 Offer 44. 数字序列中某一位的数字

题目描述

剑指 Offer 44. 数字序列中某一位的数字

image-20241107211446138

思路分析

解法一:分段定位(推荐)

核心思路

  • 将数字按位数分段:1 位数、2 位数、3 位数……
  • 每段的位数贡献为 9 * start * digits,依次扣除直到定位到目标段。
  • 在目标段中找到具体数字,再取对应位置的字符。


复杂度分析

  • 时间复杂度:O(log n),其中 n 表示输入的位数索引。
  • 空间复杂度:O(1),仅使用常数额外空间。
class Solution {
    public int findNthDigit(int n) {
        long digit = 1;
        long start = 1;
        long count = 9;

        while (n > count) {
            n -= count;
            digit++;
            start *= 10;
            count = 9 * start * digit;
        }

        long num = start + (n - 1) / digit;
        int index = (n - 1) % (int) digit;
        return String.valueOf(num).charAt(index) - '0';
    }
}
import "strconv"

func findNthDigit(n int) int {
	digit := 1
	start := 1
	count := 9

	for n > count {
		n -= count
		digit++
		start *= 10
		count = 9 * start * digit
	}

	num := start + (n-1)/digit
	index := (n - 1) % digit

	str := strconv.Itoa(num)
	return int(str[index] - '0')
}

相似题目

题目 难度 考察点
400. 第 N 位数字 中等 数学
233. 数字 1 的个数 困难 数学
357. 计算各个位数不同的数字个数 中等 数学
738. 单调递增的数字 中等 数学
1012. 至少有 1 位重复的数字 困难 数学
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/44513552
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!