给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。

注意:1 ≤ k ≤ n ≤ 109。

import java.util.Scanner;

class Solution {
public static int findKthNumber(int n, int k) {
long prefix = 1;
// 从1出发开始往后按字典序从小到大的顺序走k-1步到达的就是 字典序的第K小数字
k -= 1;

while (k > 0) {
int nodes = getNodes(n, prefix);
if (k >= nodes) {
k -= nodes;
prefix++;
} else {
k -= 1;
prefix *= 10;
}
}

return (int) prefix;
}

private static int getNodes(int n, long curPrefix) {
long nextPrefix = curPrefix + 1;
long totalNodes = 0;

while (curPrefix <= n) {
totalNodes += Math.min(n - curPrefix + 1, nextPrefix - curPrefix);

nextPrefix *= 10;
curPrefix *= 10;
}

return (int) totalNodes;
}

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(findKthNumber(in.nextInt(), in.nextInt()));
}
}
}


心之所向,素履以往 生如逆旅,一苇以航