400. Nth Digit

本文介绍了一个LeetCode上的算法题目:寻找无限整数序列中第N位数字,并提供了一种有效的C#实现方案。该算法首先确定目标数字位于几位数区间,然后找出具体数值及对应位。

原题

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.

代码实现

//for this issue, there are two different ways to decribe a number
        //1 element. this is our common way
        //2 Nth digit. this is a new way
        public int FindNthDigit(int n)
        {
            long bas = 9;
            int digits = 1, i = 0;
            //first: getting n which digit is in
            // prevent overflowing. 
            //Since bas is long, so result of bas*digits is auto imporved as long
            while (n > bas * digits) 
            {
                n -= (int)(bas * (digits++)); //nth
                i += (int)bas; //number of pasted elements
                bas *= 10; //1 digit->9; 2 digits->90; 3 digits->900, ...   
            }
            //second: Nth digit ->element
            //in all numbers containing digits, pasted numbers
            int pasted = (int)((n - 1) / digits);
            int element = pasted + i + 1;
            //third: once getting the element Nth digits stands,
            //(n-1)%digits of element is solution
            int nth = (n - 1) % digits;
            return element.ToString()[nth] - '0';
        }

leetcode-solution库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

在处理连续数字字符串(如 `0123456789101112...`)时,通常需要从字符序列中找到特定位置的数字。解决这类问题的核心在于理解数字序列的生成规律,并高效地定位到目标位置。 ### 数字字符串的生成规律 该序列由连续的自然数组成,例如 `0`、`1`、`2`、`3` ... 依次拼接为 `0123456789101112...`。每个数字的位数决定了它在序列中占用的字符数: - 1位数:`0-9`,共10个,每个占用1个字符 - 2位数:`10-99`,共90个,每个占用2个字符 - 3位数:`100-999`,共900个,每个占用3个字符 - 以此类推... 通过逐层减去字符数,可以确定目标字符位于哪个数字内。 ### 定位目标字符的步骤 1. **确定位数层级**:依次减去不同位数层级所占的字符数,直到剩余字符数小于当前层级的总字符数。 2. **确定具体数字**:计算剩余字符数与当前位数的关系,找到目标数字。 3. **确定数字中的具体位置**:提取目标数字中对应的字符。 ### 示例代码 以下是一个 Python 函数,用于找到第 `n` 位对应的数字: ```python def find_nth_digit(n): digits = 1 count = 9 start = 1 while n > digits * count: n -= digits * count digits += 1 count *= 10 start *= 10 number = start + (n - 1) // digits index_in_number = (n - 1) % digits return str(number)[index_in_number] ``` ### 代码解析 - `digits`:当前处理的数字位数(如1位、2位等) - `count`:当前位数范围内的数字数量(如1位数有10个,2位数有90个) - `start`:当前位数的第一个数字(如1位数的起始是1,2位数的起始是10) - `n`:经过逐层减去后,确定目标数字的位置 通过逐步缩小范围,最终定位到目标数字,并提取对应位置的字符。 ### 性能优化 由于直接拼接字符串效率较低(每次拼接都需要重新分配内存),因此应避免显式构造整个字符串。而是通过数学计算快速定位到目标位置。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值