440. 字典序的第K小数字
给定整数 n 和 k,找到 1 到 n 中字典序第 k 小的数字。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/k-th-smallest-in-lexicographical-order
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private long getNodes(long prefix, int n) {
long nextPrefix = prefix + 1;
long ret = 0;
while (prefix <= n) {
ret += Math.min(n - prefix + 1, nextPrefix - prefix);
prefix *= 10;
nextPrefix *= 10;
}
return ret;
}
public int findKthNumber(int n, int k) {
long prefix = 1;
while (k != 1) {
long nodes = getNodes(prefix, n);
if (nodes >= k) {
prefix *= 10;
k--;
} else {
prefix += 1;
k -= nodes;
}
}
return (int) prefix;
}
}
心之所向,素履以往 生如逆旅,一苇以航