第一次做; 核心: 1)find the length of the number where the nth digit is from; 2)find the actual number where the nth digit is from; 3)find the nth digit and return; 和我想的一样, 但是代码要比我第一版简洁太多; 但还不如最优解写得简洁; 4) count得用long类型, 10亿位数有90亿个, 超出了int的最大值21.47亿; 5) -=操作符与自动转型 6) base case后面的n都大于等于1; 记住一个案例,n=192, res=0; 跳出while循环后的n==3; 所以需要(n-1)/3
classSolution{publicintfindNthDigit(int n){if(n==0)return0;//数字的长度为len; 从长度为1的数字开始, 也就是从个位数开始int len =1;//长度为len的数字有count个long count =9;//长度为len的第一个数字int start =1;//确定第n位对应的数字的长度while(n > len*count){// n = n - len*count; //这么写会报错, 需要把count转成int
n -= len*count;//这么写就不报错了//update
len++;
start = start*10;
count = count*10;}//确定第n位对应的数字是哪个长度为len的数字
start = start +(n%len==0? n/len-1: n/len);//取出该数字的第(n-1)%len位
String s = Integer.toString(start);return Character.getNumericValue(s.charAt(n%len==0? len-1: n%len-1));}}