Leetcode 400. 第N个数字 C++

    技术2025-12-25  13

    Leetcode 400. 第N个数字

    题目

    在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …中找到第 n 个数字。

    注意: n 是正数且在32位整数范围内 ( n < 231)。

    测试样例

    示例 1:
    输入: 3 输出: 3
    示例 2:
    输入: 11 输出: 0 说明: 第11个数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是0,它是10的一部分。

    题解

    1~9,9个数,是91位数;10 ~ 99,90个数,是902位数;100 ~ 999,900个数,是900*3位数······· 对于第n位数,我们令这个数字对应的数是target,分三步

    确定找到的数是几位数,确定对应的数target是什么确定返回值是target中的哪个数字 详细过程见代码

    代码

    int findNthDigit(int n) { if(n < 10) return n; long base = 9,digit=1; while(base*digit < n){ //digit位数,就有base*digit个数,从而确定digit n -= base*digit; base *= 10; digit++; } int idx = n % digit; if(idx == 0) idx = digit; int num = base/9 + n/digit; //确定target if(idx == digit) num--; idx = digit-idx+1; while(--idx){ num /= 10; } return num%10; }

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/nth-digit 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    Processed: 0.011, SQL: 9