题解 | #数字序列中某一位的数字#
数字序列中某一位的数字
https://www.nowcoder.com/practice/29311ff7404d44e0b07077f4201418f5
import java.util.*;
public class Solution {
/**
* 解题思路:找一下规律
一位数,1-9,共9个数字,9位数字
两位数,10-99,共90个数字,180位数字
两位数,100-999,共900个数字,2700位数字
* 先锁定第n位的区间,在锁定这个区间的哪位数字
*
* @param n int整型
* @return int整型
*/
public int findNthDigit (int n) {
//记录n是几位数
int digit = 1;
// 记录当前区间的起始数字1 10 100 1000 ...
long start =1;
// 记录当前区间总共有多少位数字
long sum =9;
//1. 将n定位在某个区间内
while(n>sum){
n-=sum;
start*=10;
digit++;
//区间的总共位数
sum = 9* start*digit;
}
// 2. 定位n在哪个数字上
String num = "" + (start +(n-1) / digit);
// 3. 定位n在数字的哪一位上
int index = (n-1) % digit;
return num.charAt(index) - '0';
}
}
