[leetcode]400. Nth Digit

本文提供了一个高效的算法来解决LeetCode上的第N位数字问题,通过数学推导和编程实现,快速定位到无限整数序列中指定位置的数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://leetcode.com/problems/nth-digit/

Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...

Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).

Example 1:

Input:
3

Output:
3

Example 2:

Input:
11

Output:
0

Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
分析:

1.1位数共有9=9·1个, 1~9;

2.2位数共有90=9·10个, 10~99;

3.3位数共有900=9·10·10个, 100~999;

class Solution {
    public:
        int findNthDigit(int n) {
            int len = 1, base = 1;  // len表示当前数的位数, base表示当前位是个位、百位、千位等...
            while (n > 9L * base * len) {
                n -= 9 * base * len;
                len++;
                base *= 10;
            }
            // curNum是含有所找digit的那个数
            // n-1原因是,base比多了一位
            int curNum = (n - 1)/len + base, digit = 0;   
            for (int i = (n - 1) % len; i < len; ++i) {          // 根据偏移量找到所找的数字
                digit = curNum % 10;
                curNum /= 10;
            }
            return digit;
        }
};

class Solution{
public:
    int findNthDigit(int n)
    {
        long digit=1,ith=1,base=9;
        while(n>base*digit)
        {
            n-=base*(digit++);
            ith+=base;
            base*=10;
        }
        return to_string(ith+(n-1)/digit)[(n-1)%digit]-'0';
    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值