forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNth Digit.java
46 lines (37 loc) · 1.08 KB
/
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
// Runtime: 1237 ms (Top 5.08%) | Memory: 39.2 MB (Top 91.02%)
class Solution {
public int findNthDigit(int n) {
if(n < 10)
return n;
long currDigitIndex = 10;
int tillNextIncrease = 90;
int currNumberSize = 2;
int currNumber = 10;
int next = tillNextIncrease;
while(currDigitIndex < n) {
currNumber++;
currDigitIndex += currNumberSize;
next--;
if(next == 0) {
currNumberSize++;
tillNextIncrease *= 10;
next = tillNextIncrease;
}
}
int nthDigit = currNumber % 10;
if(currDigitIndex == n) {
while(currNumber != 0) {
nthDigit = currNumber % 10;
currNumber /= 10;
}
} else if(currDigitIndex > n) {
currNumber--;
while(currDigitIndex > n) {
currDigitIndex--;
nthDigit = currNumber % 10;
currNumber /= 10;
}
}
return nthDigit;
}
}