【题目描述】

给你一个整数 ​n​ ,请你在无限的整数序列 ​[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...]​ 中找出并返回第 ​n​ 位上的数字。

https://leetcode.cn/problems/nth-digit/description/


【示例】

【LeeCode】400. 第 N 位数字_java


【代码】​​直接计算​

题意理解看了这个图才知道一个无限的数, 第11位为是0, 因为第10位是1, 前9位分别是1, 2, 3, 4 ... 9

【LeeCode】400. 第 N 位数字_java_02

参考LeeCode的基础上, 在获取下标元素的时候采用String处理了,击败100%

【LeeCode】400. 第 N 位数字_git_03

package com.company;
// 2023-03-17

class Solution {
public int findNthDigit(int n) {
int d = 1;
int count = 9;

// 第一步: 计算出来 365 - 9 * 1 - 9 * 2 * 10 = 176
// 365是三位数中的第176个数字
while (n > (long) count * d){
n -= count * d;
d++;
count *= 10;
}

// 第二步: 假设目标数字(365)所在的数为num
// 使用目标数字在所有 3 位数中的下标进行计算,下标从 0 开始计数
int index = n - 1; // 176的下标是175
int start = (int) Math.pow(10, d - 1); // 100
int num = start + index / d; // 158

// 第三步: 获取数字的下标是第几个
// idx = 175 % 3 = 2, 说明目标数字式num=158中的第2个,即10位
int digIndex = index % d;

// 第三步: 获取第digIndex = 2的数字
// 没看懂LeeCode中 怎么用Math.pow(d - digIndex - 1)的操作
int res = Integer.parseInt(String.valueOf(num).charAt(digIndex)+"");
return res;
}
}


public class Test {
public static void main(String[] args) {
new Solution().findNthDigit(365); // 输出:3
// new Solution().findNthDigit(3); // 输出:3
// new Solution().findNthDigit(11); // 输出: 0
// new Solution().findNthDigit(1000000000); // 输出: 1
}
}


【代码】LeeCode

package com.company;
// 2023-03-17
import java.util.*;

class Solution {
public int findNthDigit(int n) {
int d = 1;
int count = 9;
// 如果一个三位数,
// n = 365 - 9 - 2 * 9 * 10
while (n > (long) d * count){
n -= d * count;
d++;
count *= 10;
}
// 这时 n=176 表示目标数字是三位数中的第 176 个数字。
int index = n - 1;
// 计算开始值, 此时 d = 3 , pow(10, 3-1)从100开始
int start = (int) Math.pow(10, d - 1);

// number = 100 + 176/3 = 158
int num = start + index / d;

// 第三步: 计算目标数字num对3取余是2, 即是158的第位
int digIndex = index % d;
// 计算第2位的数是什么
int digit = (num / (int)(Math.pow(10, d - digIndex - 1))) % 10;
// System.out.println(digit);
return digit;

}
}


public class Test {
public static void main(String[] args) {
new Solution().findNthDigit(365); // 输出:3
new Solution().findNthDigit(3); // 输出:3
new Solution().findNthDigit(11); // 输出: 0
new Solution().findNthDigit(1000000000); // 输出: 1
}
}