Appearance
44-数字序列中某一位的数字
题目描述
https://leetcode.cn/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
限制:
- 0 <= n <2^31
- 注意:本题与主站 400 题相同:https://leetcode.cn/problems/nth-digit/
思路分析
先统计每个数字所占用的位数
0 ~ 9 9*1 = 9
10 ~ 99 90*2 = 180
100 ~ 999 900*3 = 2700
1000 ~ 9999 9000*4 = 3600
规律是 9 * i * 10^i 剩余的个数为 start +
实现代码
csharp
public class Solution {
public int FindNthDigit(int n) {
int digit = 1; //对应数字的位数
long start = 1; //开始数
long count = 9; //对应位数中所有数位的总和,比如1位,就是9 ,两位就是 180, 三位就是 2700
while(n > count){
n -= (int)count;
digit++;
start *= 10;
count = digit * start * 9;
}
//从 start 开始计算位数
long num = start + (n-1) / digit;
string s = num.ToString();
return s[(n-1) % (int)digit] - '0';
}
}
AlgoPress