当前位置:网站首页>LeetCode_位数统计_中等_400.第 N 位数字
LeetCode_位数统计_中等_400.第 N 位数字
2022-08-03 20:31:00 【小城老街】
1.题目
给你一个整数 n ,请你在无限的整数序列 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …] 中找出并返回第 n 位上的数字。
示例 1:
输入:n = 3
输出:3
示例 2:
输入:n = 11
输出:0
解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, … 里是 0 ,它是 10 的一部分。
提示:
1 <= n <= 231 - 1
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/nth-digit
2.思路
(1)位数统计
思路参考该 LeetCode 用户题解。
① 分析题目可知,我们可以将该整数序列分割成无数个区间,其中每个区间内每个数的长度(即包含数字的个数)相等,这里设为 length。
length 区间 包含数字的个数
1 [1, 9] 9 * 1 = 9 * 10^0 * 1
2 [10, 99] 90 * 2 = 9 * 10^1 * 2
3 [100, 999] 900 * 3 = 9 * 10^2 * 3
4 [1000, 9999] 9000 * 4 = 9 * 10^3 * 4
... ... ...
k [10^(k - 1), 10^k - 1] 9 * 10^(length - 1) * length
... ... ...
② 根据上面的规律,我可以先计算出第 n 位上的数字所属的数的长度 length,然后再计算出第 n 位上的数字所属的数(设为 num),最后再计算对应位上的数字即可,具体的分析过程可见下面代码中的注释。
3.代码实现(Java)
//思路1————
class Solution {
public int findNthDigit(int n) {
// 设第 n 位上的数字所属的数为 num,其长度 length,其初始值为 1
int length = 1;
while (9 * Math.pow(10, length - 1) * length < n) {
n -= 9 * Math.pow(10, length - 1) * length;
length++;
}
// res 保存结果
int res = 0;
// num 所在的区间为 interval = [10^(length - 1), 10^length - 1],设 start 为该区间的起点
long start = (long) Math.pow(10, length - 1);
// 由于 interval 内每个数的长度相等,故此时剩余的 n 除以 length 就等于 num 到 s 的偏移量
long num = start + n / length - 1;
// 计算 res 离 num 的最后一个数字的距离 dis
int dis = n - length * (n / length);
if (dis == 0) {
// dis 正好为 0,那么 res 就是 num 的最后一个数字,即个位上的数字
res = (int) (num % 10);
} else {
res = (int) ((num + 1) / Math.pow(10, length - dis) % 10);
}
return res;
}
}
边栏推荐
猜你喜欢
Likou 707 - Design Linked List - Linked List
2022年强网杯rcefile wp
tRNA修饰2-甲基胞嘧啶(m2C)|tRNA修饰m2G (N2-methylguanosine)
数学之美 第六章——信息的度量和作用
收藏-即时通讯(IM)开源项目OpenIM-功能手册
Edge box + time series database, technology selection behind Midea's digital platform iBuilding
RNA-ATTO 390|RNA-ATTO 425|RNA-ATTO 465|RNA-ATTO 488|RNA-ATTO 495|RNA-ATTO 520近红外荧光染料标记核糖核酸RNA
利用 rpush 和 blpop 实现 Redis 消息队列
收藏-即时通讯(IM)开源项目OpenIM-功能手册
数据库定时备份winserver2012篇
随机推荐
倒计时2天,“文化数字化战略新型基础设施暨文化艺术链生态建设发布会”启幕在即
极验深知v2分析
codeforces:C. Maximum Subrectangle【前缀和 + 贪心 + 最小子数组和】
tkwebview2创作心得
第三方验收测试报告有什么作用?如何获取权威软件测试报告?
leetcode 1837. K 进制表示下的各位数字总和
Matlab paper illustration drawing template No. 42 - bubble matrix diagram (correlation coefficient matrix diagram)
Likou 707 - Design Linked List - Linked List
力扣707-设计链表——链表
Power button 206 - reverse list - the list
ES6--剩余参数
ES6 deconstruction assignment - array object deconstruction and deconstruction
EMQX Newsletter 2022-07|EMQX 5.0 正式发布、EMQX Cloud 新增 2 个数据库集成
Hinton2022年RobotBrains访谈记录
leetcode 231. 2 的幂
收藏-即时通讯(IM)开源项目OpenIM-功能手册
消除对特权账户的依赖使用Kaniko构建镜像
抖音web逆向教程
利用 rpush 和 blpop 实现 Redis 消息队列
tRNA-m5C转运RNA(tRNA)修饰5-甲基胞嘧啶(m5C)|tRNA修饰m1Am2A (2-methyladenosine)