LeetCode 400. Nth Digit
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input: 3 Output: 3
Example 2:
Input: 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
题目标签:Math
题目给了我们一个 number n,让我们找到 第n个 digit。
首先来看一下规律:
start - range len
number 1 - 9 1 digit
10 - 99 2 digits
100 - 999 3 digits
...
想法是,首先我们要找到 第n个 digit 是在哪一个 range 里的,然后通过计算找出digit。
我们从1 - 9 开始,这里有 9 个digits,如果 n 大于 9,那么digit 肯定在更大的 range 里,继续loop。
我们需要初始 len = 1; range = 9; start = 1;
len 是一个个的增加;
range 是 10倍的增加, 1-9 是 9个; 10 - 99 是 90个;100 - 999 是 900个 ...
start 也是 10倍的增加,1, 10, 100 ...
当我们找到具体在哪一个 range 里之后,可以利用 (n-1) / len + start 来找到具体的 number;
在利用 (n-1) % len 来找到具体的 digit。
Java Solution:
Runtime beats 91.87%
完成日期:06/16/2017
关键词:math
关键点:用 / 来找到number;用 % 来找到 digit
1 class Solution 2 { 3 public int findNthDigit(int n) 4 { 5 // initial vars 6 long len = 1; 7 long range = 9; 8 long start = 1; 9 10 while(n > (len * range)) // find n is in which range 11 { 12 n = n - (int)len * (int)range; // minus the current total range digits 13 // move to next range 14 len++; 15 range *= 10; 16 start *= 10; 17 } 18 19 // now is in the correct range 20 start = start + (n-1) / len; // find the number 21 String num = "" + start; 22 int d = num.charAt( (n-1) % (int)len ) - '0'; 23 24 return d; 25 } 26 }
参考资料:http://www.cnblogs.com/grandyang/p/5891871.html
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· MQ 如何保证数据一致性?