Skip to content

Commit d505d83

Browse files
authored
Create 440. K-th Smallest in Lexicographical Order1 (#592)
2 parents 5120c5a + 1329d51 commit d505d83

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
long countSteps(long prefix, long n) {
4+
long steps = 0, nextPrefix = prefix + 1;
5+
while (prefix <= n) {
6+
steps += min(n + 1, nextPrefix) - prefix;
7+
prefix *= 10;
8+
nextPrefix *= 10;
9+
}
10+
return steps;
11+
}
12+
13+
int findKthNumber(int n, int k) {
14+
int curr = 1;
15+
k--;
16+
while (k > 0) {
17+
long steps = countSteps(curr, n);
18+
if (steps <= k) {
19+
curr++;
20+
k -= steps;
21+
} else {
22+
curr *= 10;
23+
k--;
24+
}
25+
}
26+
return curr;
27+
}
28+
};

0 commit comments

Comments
 (0)