剑指 Offer 44. 数字序列中某一位的数字
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/shu-zi-xu-lie-zhong-mou-yi-wei-de-shu-zi-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
- 将 n 看做数位,求出数字的位数 digit 和每位的起始数字 start,用于反推这个数字,再通过 n % digit 推出结果。
- 第一步:当 n > count 时,n -= count,总数从第一位开始减,确定数字在哪个位 digit 上,起始的位置 start
- 第二步,反推 num 是多少:num = (n - 1) * digit。n - 1 是因为 start 从 0 开始
- 第三步,截取数字中的结果值,用 n - 1 对 digit 取模,n - 1 是因为 start 从 0 开始 要注意数字会超过 int 最大值,所以 start count num 都需要申明为 long
代码
解法一
class Solution {
public int findNthDigit(int n) {
int digit = 1;
long start = 1, count = 9;
while (n > count) {
n -= count;
start *= 10;
digit += 1;
count = 9 * start * digit;
}
long num = start + (n - 1) / digit;
return Long.toString(num).charAt((n - 1) % digit) - '0';
}
}
本文由 Meridian 创作,采用 知识共享署名4.0
国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Mar 16,2022