解法一(不完全对的解法,对于n很大时会造成内存溢出):
public class Solution {
//将一个树n按位拆分,并存入list容器中
public void split(List<Integer> list, int n){
LinkedList<Integer> temp = new LinkedList<>();
while(n != 0){
temp.addFirst(n % 10);
n /= 10;
}
list.addAll(temp);
}
public int findNthDigit(int n) {
LinkedList<Integer> list = new LinkedList<>();
//将从1到n的数都按位拆分,存入List容器中,因为后面会有多位数,所以list的元素个数一定大于n
for(int i = 1; i <= n; i++){
split(list, i);
}
return list.get(n - 1);//返回指定位数的数
}
}
解法二(正解):
public class Solution {
//就是一个数学问题,观察,总结出规律
/*Idea:
The first idea is: the result will only be within 0~9, can we find a cycle?
For input 1 to 20, the result is:
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5
No cycle found. While we can find that digits matter! The result sequence should be like:
1~9: 1*9=9 in total
10~99: 2*90=180 in total
100~999: 3*900=2700 in total
Then, 49000, 590000, k*9*10^(k-1)
一些例子(左边那列是n,右边那列是第n位对应的数)
12342 3
12343 3
12344 6
12345 3
For input 12345, we have 9+180+2700 < 12345 < 9+180+2700+36000, so the corresponding number is 1000+.
12345-9-180-2700=9456
9456/4 = 2364...0,
同理,对于12342, 12342-9-180-2700=9453, 9453/4 = 2363...1
对于12343, 12343-9-180-2700=9454, 9454/4 = 2363...2
对于12344, 12344-9-180-2700=9455, 9455/4 = 2363...3
对于12345, 12345-9-180-2700=9456, 9456/4 = 2364...0
总结规律:12342是四位数的第2363组的第1位数,即1000+2363=3363的第1位数:3
12343是四位数的第2363组的第2位数,即1000+2363=3363的第2位数:3
12344是四位数的第2363组的第3位数,即1000+2363=3363的第3位数:6
12345是四位数的第2363组的第4位数,即1000+2363=3363的第4位数:3
即可以总结出算法了
*/
public int findNthDigit(int n) {
if(n < 10)
return n;
long count = 1L;//用于记录10的幂,即上面所说的k*9*10^(k-1)中的10^(k-1),这里k即为bit
//这里用Long的原因是当count=1000000000时如果再乘10会溢出int的最大值
int bit = 1;//记录当前到第几位数了
int t = n;
while(t - bit*9*count > 0){//这个循环用于判断,如何体现9+180+2700 < 12345 < 9+180+2700+36000
t -= bit*9*count;//不能放到循环体的最后,因为在循环体的最后bit和count都发生变化了
count = count * 10;
bit++;
//System.out.println("bit " + bit + " count " + count);
//System.out.println("bit " + bit + " count " + Integer.MAX_VALUE);
}
int div = t / bit;
int mod = t % bit;
if(mod == 0){//特殊情况 12345-9-180-2700=9456, 9456/4 = 2364...0 12345是四位数的第2363组的第4位数,即1000+2363=3363的第4位数:3
div = div - 1;
int data = (int) (count + div);
return data % 10;
}
else{
int data = (int) (count + div);
//System.out.println("div : " + div);
//System.out.println("mod : " + mod);
//System.out.println("data : " + data);
for(int i = 1; i < mod; i++){
data = (int) (data - (data / count) * count);
count = count / 10;
//System.out.println("count : " + count);
//System.out.println("data : " + data);
}
return (int) (data / count);
}
}
}