题目:
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
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步,求出对应的number应该是几位数——digit。
- 第2步,求出该number在所有digit位数中排第几——quotient(从0开始),求出n对应位是该number的第几位——remainder(0代表最高位)。
第3步,求出结果,如果是最高位,需要加1,因为最高位从1开始。
注意:quotient/(int)Math.pow(10,digit-remainder-1)%10的写法我想了好久,毕竟数目只能是0~9,结尾应该有
%10
。/(int)Math.pow(10,digit-remainder-1)
是取出该位数字
代码:
public class Solution {
public int findNthDigit(int n) {
// find the digit and the position in current digit
int digit = 1; // digit
long base = 9; // the number of every digits:9,9*2*10,9*3*100
while(n-base>0){
n-=base;
digit++;
base=base/(digit-1)*digit*10;
}
// pos start from 0, than remainder==0 mains the highest digit when digit=1 or digit>1.
// if pos start from 1, than remainder==0 mains the highest digit when digit=1.And remainder==1 mains the highest digit when digit>1
n--;
int quotient = n/digit; // which num
int remainder = n%digit; // which digit of num
if(remainder==0){
return quotient/(int)Math.pow(10,digit-remainder-1)%10+1;// highest digit start from 1
}else{
return quotient/(int)Math.pow(10,digit-remainder-1)%10;// other digit start from 0
}
}
}