440.k-th-smallest-in-lexicographical-order.java 648 B

123456789101112131415161718192021222324
  1. class Solution {
  2. public int findKthNumber(int n, int k) {
  3. int cur = 1;
  4. k--;
  5. // Ten-ary tree
  6. while (0 < k) {
  7. int cnt = 0;
  8. long lo = cur, hi = cur + 1;
  9. while (lo <= n) {
  10. cnt += (int) (Math.min(hi, n + 1) - lo);
  11. lo *= 10;
  12. hi *= 10;
  13. } // Count the number of children level by level
  14. if (cnt <= k) {
  15. cur++; // Go to next child
  16. k -= cnt;
  17. } else {
  18. cur *= 10; // Go to next level
  19. k--;
  20. }
  21. }
  22. return cur;
  23. }
  24. }