数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
限制:
0 <= n < 2^31
解题思路:
法1:寻找不同位数的规律:
m位数 | m位数总数 | m位数总数字数 | 前m位数总数字数-1 |
---|---|---|---|
1 | 10(0-9) | 1*10(0-9) | |
2 | 90(10-99) | 2*90 | |
3 | 900(100-999) | 3*900 | |
4 | 9000(1000-9999) | 4*9000 | |
n | 9*10^(m-1) | m*9*10^(m-1) | (m-1/9)*10^m+1/9 |
(1)首先确定n是几位数中的数字,和(m-1/9)*10^m+1/9进行比较,
当((m-1)-1/9)*10^(m-1)+1/9<n<=(m-1/9)*10^m+1/9时,可判断出n时m位数中的数字。
(2)其次确定n是m位数中的哪一个数中的数字。另(n-((m-1)-1/9)*10^(m-1)+1/9)/m向上取整得到n是m位数中的第k个数,计算第k个数target=10^(m-1) + k - 1。
(3)最后确定n是target中的第几个数字并返回这个数字。另(n-((m-1)-1/9)*10^(m-1)+1/9)%m,余数是0则是最后一位,余数是其他值就是第余数位,返回这一位的值。
class Solution {
public int findNthDigit(int n) {
if(n < 10) return n;
double wei = 1.0;
int cnt = 9;
while(n > cnt){
wei++;
cnt = (int)((wei - 1./9) * Math.pow(10, wei) + 1. / 9);
}
int temp = n - (int)(((wei - 1) - 1./9) * Math.pow(10, (wei - 1)) + 1. / 9);
int shu = (int)Math.ceil(temp / wei);
int tar = (int)Math.pow(10, wei - 1) + shu - 1;
int ret = (int)(tar / (Math.pow(10, wei - ((temp % wei == 0) ? wei : (temp % wei))))) % 10;
return ret;
}
}
注意:int数和double数运算结果会变int,需要进行数据转换。
法2:同样是找规律:
class Solution {
public int findNthDigit(int n) {
int digit = 1;
long start = 1;
long count = 9;
while (n > count) { // 1.
n -= count;
digit += 1;
start *= 10;
count = digit * start * 9;
}
long num = start + (n - 1) / digit; // 2.
return Long.toString(num).charAt((n - 1) % digit) - '0'; // 3.
}
}
作者:jyd
链接:https://leetcode.cn/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof/solution/mian-shi-ti-44-shu-zi-xu-lie-zhong-mou-yi-wei-de-6/
来源:力扣(LeetCode)