-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathoffer44.java
More file actions
59 lines (53 loc) · 1.55 KB
/
offer44.java
File metadata and controls
59 lines (53 loc) · 1.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* [44] 数字序列中某一位的数字
*
* 题目: 数字以 0123456789101112131415... 的格式序列化到一个字符序列中. 在这个序列中, 第 5 位(从下标 0 开始计数)是 5, 第 13 位是 1,
* 第 19 位是 4, 等等. 返回任意第 n 位对应的数字.
*
* 思路: 找规律.
*/
class Solution {
/**
* 时间复杂度: O()
* 空间复杂度: O()
*/
public int findNthDigit(int n) {
if (n < 0) {
return -1;
}
// place represent digit's position numbers.
int place = 1;
while (true) {
int numbers = countNumbers(place) * place;
if (n < numbers) {
return getDigitAtN(n, place);
}
n -= numbers;
place++;
}
}
// get 'place' positions digit form string's length.
// 10, 90, 900, ...
private int countNumbers(int place) {
if (place == 1) {
return 10;
}
return (int) Math.pow(10, place - 1) * 9;
}
// find nth number in 'place' position digit form string.
private int getDigitAtN(int n, int place) {
int beginNum = getBeginNum(place);
int offset = n / place;
String number = beginNum + offset + "";
int position = n % place;
return number.charAt(position) - '0';
}
// get 'place' positions digit's first digit.
// 0, 10, 100
private int getBeginNum(int place) {
if (place == 1) {
return 0;
}
return (int) Math.pow(10, place - 1);
}
}