440. lexicographically small number of K
Given integers n and k, n are lexicographically found small numbers 1 to k.
Note: 1 ≤ k ≤ n ≤ 109.
Example:
Input:
n-: 13 is K: 2
Output:
10
Explanation: The
arrangement is lexicographically [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], the second number is smaller 10.
PS:
ten tree
class Solution {
public int findKthNumber(int n, int k) {
int cur = 1;
k--;
while (k > 0) {
long step = 0, first = cur, last = cur + 1;
while (first <= n) {
step += Math.min(last, (long) (n + 1)) - first;
first *= 10;
last *= 10;
}
if (step > k) {
//在树里
k--;
cur *= 10;
}
if (step <= k) {
//不在树里
k -= step;
++cur;
}
}
return cur;
}
}