Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

400. Nth Digit #138

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

思路:可以分三步来做:

1.找出给定的n落在几位数的范围内

2.找到具体落在哪个数字

3.找出具体在哪一位上

分析可以得出一位有9个数字,二位数有90个数字,三位数有900个数,依次类推.因此可以每次增加一位数字,看n是否还在这个范围内.例如给定n = 150,首先一位有9个数字,所以位数可以+1,这样n-9 = 141. 然后2位的数字有2*90= 180,大于141,所以目标数字肯定是2位的.然后求具体落在哪个数字.可以用10+(141-1)/2 = 80求出.再求具体落在哪一位上,可以用(141-1)%2=0求出为第0位,即8.如此即可.

public class Solution { public int findNthDigit(int n) { if(n < 10) return n; //base的意思是代表有几位数 int base = 1; while(n > 9Math.pow(10, base-1)base) { n -= 9 Math.pow(10, base-1) base; base++; } //比如这个数是三位数,n减去1的原因是除去100这个数 int number = (int)Math.pow(10, base-1) + (n-1)/base; //找到是该数中的第几个数字 int index = (n-1) % base; return Integer.toString(number).charAt(index) - '0'; } }

Shawngbk commented 7 years ago

google