https://leetcode.com/problems/nth-digit/description/
int findNthDigit(int n) {
vector<int> sd(9,0);
int d;
for(d=1; d<9; d++) {
// d is the length (digits of a single number) of a number
// sd is the total digits for length from 1 to d
sd[d] = d*pow(10, d) - (pow(10,d)-1)/9;
if(sd[d]>=n) break;
}
// the length of number prior to the current length
int d1 = d-1;
// total digits for length d is n - total digits for length from 1 to d-1
n -= sd[d1];
// the number is i-th of numbers with length d
int i = (n-1)/d;
// the first number of length d is
int a = pow(10, d1);
// what is the number
a += i;
// the digit is the i-th digit of the number a
i = n - i*d;
// return the digit
return (a/(int)(pow(10,d-i))) % 10;
}
No comments:
Post a Comment