Google
400 Nth Digit

400. Nth Digit

1. Question

Find thenthdigit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note: nis positive and will fit within the range of a 32-bit signed integer (n< 231).
Example 1:
1
Input: 3
2
3
Output: 3
Copied!
Example 2:
1
Input: 11
2
3
Output: 0
4
5
Explanation:
6
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.
Copied!

2. Implementation

(1) Math
1
class Solution {
2
public int findNthDigit(int n) {
3
// 记录target number的长度
4
int digits = 1;
5
// 这里要用Long防止overflow
6
long count = 9;
7
int startNum = 1;
8
9
// Step 1: 找到第n个 digit所在的数的长度
10
while (n > count * digits) {
11
n -= count * digits;
12
digits += 1;
13
count *= 10;
14
startNum *= 10;
15
}
16
17
// Step 2:找到target number
18
int target = start + (n - 1) / digits; //减一是因为start本身算一个数
19
String s = Integer.toString(target); // 将target转成字符串方便下一步找到nth digit
20
21
// Step 3: (n - 1) % digits是nth digit在target number的位置
22
return Character.getNumericValue(s.charAt((n - 1) % digits));
23
}
24
}
Copied!

3. Time & Space Complexity

时间复杂度O(logN), log的底是10, 空间复杂度O(1)