Skip to content

Commit 03aaf46

Browse files
authored
Create 440. K-th Smallest in Lexicographical Order (#812)
2 parents fdf2233 + e40ba05 commit 03aaf46

File tree

1 file changed

+32
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)