题目
数字以0123456789101112131415…的格式序列化到一个字符序列中。
在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第 n 位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
限制:
0 <= n < 2^31
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof
解题思路
解题思路引用自作者:z1m
找规律
-
通过观察,可以发现以下规律:
-
对于第 n 位对应的数字,我们令这个数字对应的数为 target,然后分三步进行。
- 首先找到这个数字对应的数有几位,用 digits 表示;
- 再确定这个对应的数的数值 target;
- 最后确定返回值是 target 中的哪个数字。
举例
如:输入 n = 365:
-
第一步
- 计算我们可以得到第 365 个数字表示的数是三位数
- n = 365 - 9 - 90 * 2 = 176 ,digtis = 3。
- 这时 digtis = 3 表示目标数字是三位数,n = 176 表示数字序列中的第 176 个。
- 计算我们可以得到第 365 个数字表示的数是三位数
-
第二步
- 用 first_num 表示每组数的第一个数。
- 计算该数值范围的起始数值
- first_num := Math.pow ( 10 , digits - 1 )
- 计算剩余补充数值
- supply_num = n / digits
- 设目标数字所在的数为 target ,计算得到
- targetr = first_num + supply_num = 100 + 176 / 3 = 158
- 用 first_num 表示每组数的第一个数。
-
第三步
- idx 是目标数字在 target 中的索引
- 计算可得 idx = n % digits = 176 % 3 = 2
- idx = 2 说明目标数字应该是 target = 158 中的第二个数字,即输出为 5。
- 如果 idx = 0,表示目标数字是 target 中的最后一个数字。
- idx 是目标数字在 target 中的索引
代码
–执行用时:0 ms --内存消耗:1.9 MB
func findNthDigit(n int) int {
if n < 10 {
return n
}
//1、计算当前范围有几位数字
digits := 0
for n > count(digits){
n -= count(digits)
digits++
}
//2、确定具体是哪个数
//Math.pow(10,digits-1) -- 起始数值
first_num := int(math.Pow(10.0,float64(digits-1)))
// n/digits -- 剩余补充数值
supply_num := n / digits
target := first_num + supply_num
//3、余数计算是该数的第几位
idx := n % digits
return int(strconv.Itoa(target)[idx]) - '0'
}
//count 计算当前有多少位 如:1位数10种,10位;2位数 90个数字 180位;3位数 900个 2700位
func count(n int)int{
if n == 0{
return 1
}
return int(math.Pow(10.0,float64(n-1)))*9*n
}