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).
这道题有点意思
public int findNthDigit(int n) {
long i = 0;
int start = 1;
int len = 1;
long val = 9; //注意溢出
//找到落在哪个区域
while(n > ( i = len * val)){
n -= i; //注意溢出?
len ++;
val = val * 10;
start = start * 10;
}
//找到对应数字是多少
int num = start + (n - 1)/len;
//找到对应数字的位数
String s = Integer.toString(num);
return Character.getNumericValue(s.charAt((n - 1) % len));
}
网友评论