K-th Smallest in Lexicographical Order

Given integers n and k, find the lexicographically k-th smallest integer in the range from 1 to n.

Note: 1 ≤ k ≤ n ≤ 109.

Example:

Input:
n: 13   k: 2

Output:
10

Explanation:
The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.

Solution:

class Solution {
    public int findKthNumber(int n, int k) {
        int result = 1;
        for (k --; k > 0; ) {
            int count = 0;
            for (long first = result, last = first + 1; first <= n; first *= 10, last *= 10) {
                count += (int) (Math.min(last, n + 1) - first);
            }
            if (k >= count) {
                k -= count;
                result ++;
            } else {
                k --;
                result *= 10;
            }
        }
        return result;
    }
}