Description
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).
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.
Solution
Math
很多细节需要注意!
class Solution {
public int findNthDigit(int n) {
int len = 1;
int base = 1;
while (n > 9L * base * len) { // watch out for overflow!
n -= 9 * base * len;
base *= 10;
++len;
}
// don't forget to minus 1 because base matters
return getDigit(base + (n - 1) / len, len - (n - 1) % len);
}
// if n = 6104 and i = 2, return 0
public int getDigit(int n, int i) {
while (i > 1) {
n /= 10;
--i;
}
return n % 10;
}
}