171.Nth Digit
题目:
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
找到无限整数序列的第n个数字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).
n为正且将适合32位有符号整数(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 10.
序列1,2,3,4,5,6,7,8,9,10,11 ......的第11位是0,它是数字10的一部分。
解答:
1 class Solution { 2 public int findNthDigit(int n) { 3 int len=1; 4 long count=9; 5 int start=1; 6 7 while(n>len*count){ 8 n-=len*count; 9 len+=1; 10 count*=10; 11 start*=10; 12 } 13 14 start+=(n-1)/len; 15 String s=Integer.toString(start); 16 return Character.getNumericValue(s.charAt((n-1)%len)); 17 } 18 }
详解:
1~9 9个数 9*1=9个数字
10~99 90个数 90*2=180个数字
100~999 900个数 900*3=2700个数字
故count初始化为9,每次循环扩大10倍。len为当前循环数字的位数,start为当前循环的第一个数字。
1.找到第n个数字所在的数字长度
2.找到第n个数字实际所在的数字
3.找到第n个数字返回