-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path400. Nth Digit.java
46 lines (40 loc) · 1.23 KB
/
400. Nth Digit.java
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
// Brute (Memory Limit)
public class Solution {
public int findNthDigit(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 1; ; i++) {
sb.append(i);
if (sb.length() >= n) {
return sb.charAt(n-1) - '0';
}
}
}
}
// Space improvement (Time Limit)
public class Solution {
public int findNthDigit(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 1; ; i++) {
sb.append(i);
if (n > sb.length()) {
n -= sb.length();
sb.delete(0, sb.length());
} else {
return sb.charAt(n-1) - '0';
}
}
}
}
// Space and Time improvement https://discuss.leetcode.com/topic/59378/short-python-java
// Rather than iterate single number, move up in range 1-9, 10-99, 100-999, 1000-999
// First number in range + Left over (n*) / digits = Actual number
public int findNthDigit(int n) {
n -= 1;
int digits = 1, first = 1;
while (n / 9 / first / digits >= 1) {
n -= 9 * first * digits;
digits++;
first *= 10;
}
return (first + n/digits + "").charAt(n%digits) - '0';
}