Easy to understand JS solution


  • 1
    // Calculates the amount of
    // numbers <= n that starts with prefix.
    
    function countForPrefix (n, prefix) {
        let a = parseInt(prefix);
        let b = a + 1;
        if (a > n || a === 0)
            return 0;
    
        let res = 1;
        a *= 10; b *= 10;
        while (a <= n) {
            res += Math.min(n + 1, b) - a;
            a *= 10; b *= 10;
        }
    
        return res;
    }
    
    // Constructs resulting number digit by digit
    // starting with the most significant.
    
    function findKthNumber (n, k) {
        let i, prefix = '';
        while (k !== 0) {
            for (i = 0; i <= 9; i++) {
                const count = countForPrefix(n, prefix + i);
                if (count < k)
                    k -= count;
                else
                    break;
            }
            prefix = prefix + i;
            k--; // number equal to prefix
        }
    
        return parseInt(prefix, 10);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.