400:第 N 位数字
This commit is contained in:
parent
8df9e1abb1
commit
b00057e39f
52
src/main/java/leetcode/editor/cn/NthDigit.java
Normal file
52
src/main/java/leetcode/editor/cn/NthDigit.java
Normal file
@ -0,0 +1,52 @@
|
||||
//在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 位数字。
|
||||
//
|
||||
//
|
||||
//
|
||||
// 注意:n 是正数且在 32 位整数范围内(n < 231)。
|
||||
//
|
||||
//
|
||||
//
|
||||
// 示例 1:
|
||||
//
|
||||
//
|
||||
//输入:3
|
||||
//输出:3
|
||||
//
|
||||
//
|
||||
// 示例 2:
|
||||
//
|
||||
//
|
||||
//输入:11
|
||||
//输出:0
|
||||
//解释:第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 0 ,它是 10 的一部分。
|
||||
//
|
||||
// Related Topics 数学 二分查找
|
||||
// 👍 170 👎 0
|
||||
|
||||
package leetcode.editor.cn;
|
||||
//400:第 N 位数字
|
||||
class NthDigit{
|
||||
public static void main(String[] args) {
|
||||
//测试代码
|
||||
Solution solution = new NthDigit().new Solution();
|
||||
}
|
||||
|
||||
//力扣代码
|
||||
//leetcode submit region begin(Prohibit modification and deletion)
|
||||
class Solution {
|
||||
public int findNthDigit(int n) {
|
||||
int[] ant = new int[]{0, 10, 190, 2890, 38890, 488890, 5888890, 68888890, 788888890};
|
||||
int[] numBegin = new int[]{0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000};
|
||||
for(int i = ant.length - 1; i >= 0; i--){
|
||||
if(n >= ant[i]){
|
||||
int num = (n - ant[i]) / (i + 1) + numBegin[i];
|
||||
int posi = (n - ant[i]) % (i + 1);
|
||||
return num % (int)Math.pow(10, i + 1 - posi) / (int)Math.pow(10, i - posi);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
//leetcode submit region end(Prohibit modification and deletion)
|
||||
|
||||
}
|
23
src/main/java/leetcode/editor/cn/NthDigit.md
Normal file
23
src/main/java/leetcode/editor/cn/NthDigit.md
Normal file
@ -0,0 +1,23 @@
|
||||
<p>在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 <code>n</code><em> </em>位数字。</p>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>注意:</strong><code>n</code><em> </em>是正数且在 32 位整数范围内(<code>n < 2<sup>31</sup></code>)。</p>
|
||||
|
||||
<p> </p>
|
||||
|
||||
<p><strong>示例 1:</strong></p>
|
||||
|
||||
<pre>
|
||||
<strong>输入:</strong>3
|
||||
<strong>输出:</strong>3
|
||||
</pre>
|
||||
|
||||
<p><strong>示例 2:</strong></p>
|
||||
|
||||
<pre>
|
||||
<strong>输入:</strong>11
|
||||
<strong>输出:</strong>0
|
||||
<strong>解释:</strong>第 11 位数字在序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... 里是 <strong>0 </strong>,它是 10 的一部分。
|
||||
</pre>
|
||||
<div><div>Related Topics</div><div><li>数学</li><li>二分查找</li></div></div>\n<div><li>👍 170</li><li>👎 0</li></div>
|
Loading…
Reference in New Issue
Block a user