-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet1.java
More file actions
30 lines (29 loc) · 814 Bytes
/
Copy pathleet1.java
File metadata and controls
30 lines (29 loc) · 814 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
class Solution {
public:
int findKthNumber(int n, int k) {
int currentPrefix = 1;
--k;
while (k > 0) {
int count = countNumbersWithPrefix(currentPrefix, n);
if (k >= count) {
++currentPrefix;
k -= count;
} else {
currentPrefix *= 10;
--k;
}
}
return currentPrefix;
}
private:
int countNumbersWithPrefix(int prefix, int n) {
long long firstNumber = prefix, nextNumber = prefix + 1;
int totalCount = 0;
while (firstNumber <= n) {
totalCount += static_cast<int>(min(n + 1LL, nextNumber) - firstNumber);
firstNumber *= 10;
nextNumber *= 10;
}
return totalCount;
}
};