问题:
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input: 3 Output: 3
Example 2:
Input: 11 Output: 0 Explanation: The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number.
解决:
【注】问题的本意是将所有的自然数看成一个字符串,输出第n位上的数是多少。
① 问题的本质在于找到这个字符串中第n位上是多少。我们可以知道:
1 - 9 : 9
10 - 99 : 90 * 2
100 - 999 : 900 * 3
1000 - 9999 : 9000 * 4
... ...
我们可以定义个变量count,初始化为9,然后每次循环扩大10倍,再用一个变量len记录当前循环区间数字的位数,另外再需要一个变量start用来记录当前循环区间的第一个数字,我们n每次循环都减去len*count(区间总位数),当n落到某一个确定的区间里了,那么(n-1)/len就是目标数字在该区间里的坐标,加上start就是得到了目标数字,然后我们将目标数字start转为字符串,(n-1)%len就是所要求的目标位,最后别忘了考虑int溢出问题,我们干脆把所有变量都申请为长整型的。
例如,定义n = 1000,首先,1000-9=991,991-180=811。剩下的数为811,第1000位所在的数为100+(811-1)/3=370,第1000位的数在370中的序列号为(811-1)%3=0,所以结果为第0位上的3.
public class Solution { //6ms
public int findNthDigit(int n) {
if(n <= 0) return 0;
long count = 9;
int start = 1;
int len = 1;
while(n > len * count){ //每个区间的总位数
n -= len * count;
len ++;
start *= 10;
count *= 10;
}
start += (n - 1) /l en;
return String.valueOf(start).charAt((n - 1) % len) -'0';
}
}