-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path572.java
More file actions
32 lines (27 loc) · 915 Bytes
/
Copy path572.java
File metadata and controls
32 lines (27 loc) · 915 Bytes
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
class Solution {
public int findKthNumber(int n, int k) {
int currentPrefix = 1;
k--; // Decrement k to handle zero-based indexing
while (k > 0) {
int count = countNumbersWithPrefix(currentPrefix, n);
if (k >= count) {
currentPrefix++; // Move to the next prefix
k -= count;
} else {
currentPrefix *= 10; // Go deeper in the current prefix
k--;
}
}
return currentPrefix;
}
private int countNumbersWithPrefix(int prefix, int n) {
long firstNumber = prefix, nextNumber = prefix + 1;
int totalCount = 0;
while (firstNumber <= n) {
totalCount += Math.min(n + 1, nextNumber) - firstNumber;
firstNumber *= 10;
nextNumber *= 10;
}
return totalCount;
}
}