当前位置:网站首页>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;
}
}
边栏推荐
- 李沐动手学深度学习V2-BERT微调和代码实现
- In-depth understanding of JVM-memory structure
- svg+js订单确认按钮动画js特效
- Go语言为任意类型添加方法
- 盲埋孔PCB叠孔设计的利与弊
- 直播源码开发,各种常见的广告形式
- The sword refers to Offer II 044. The maximum value of each level of the binary tree-dfs method
- leetcode 899. 有序队列
- NAACL 2022 | 具有元重加权的鲁棒自增强命名实体识别技术
- Matlab paper illustration drawing template No. 42 - bubble matrix diagram (correlation coefficient matrix diagram)
猜你喜欢
随机推荐
TweenMax.js向日葵表情变化
【HiFlow】经常忘记签到怎么办?使用腾讯云场景连接器每天提醒你。
leetcode 326. Powers of 3
李沐动手学深度学习V2-BERT微调和代码实现
charles配置客户端请求全部不走缓存
8.2模拟赛总结
若依集成easyexcel实现excel表格增强
ARMuseum
染料修饰核酸RNA|[email protected] 610/[email protected] 594/Alexa 56
李沐动手学深度学习V2-自然语言推断与数据集SNLI和代码实现
leetcode 268. Missing Numbers (XOR!!)
Kubernetes资源编排系列之三: Kustomize篇 作者 艄公(杨京华) 雪尧(郭耀星)
tRNA甲基化偶联3-甲基胞嘧啶(m3C)|tRNA-m3C (3-methylcy- tidine)
极验深知v2分析
力扣206-反转链表——链表
在树莓派上搭建属于自己的网页(3)
chartjs自定义柱状图插件
wordpress建立数据库连接时出错
信使mRNA甲基化偶联3-甲基胞嘧啶(m3C)|mRNA-m3C
EasyCVR平台海康摄像头语音对讲功能配置的3个注意事项



![【微信小程序2】事件传参与数据同步[03]](/img/d9/73004e6edf800c583231a94dfbd878.png)


[email protected] 594/

