<p>Given two integers <code>n</code> and <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>lexicographically smallest integer in the range</em> <code>[1, n]</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 13, k = 2
<strong>Output:</strong> 10
<strong>Explanation:</strong> The lexicographical order is [1, 10, 11, 12, 13, 2, 3, 4, 5, 6, 7, 8, 9], so the second smallest number is 10.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1, k = 1
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>9</sup></code></li>
</ul>

class Solution {
public:

    int lenNum(int x){
        if (x < 10) return 1;
        return 1 + lenNum(x/10);
    }

    int subNum(int n, int k){
        int h = lenNum(n);
        for (h = max(0, h - k); h; h--) n /= 10;
        return n;
    }

    int counting(int left, int maximum, int len){
        if (left > maximum) return 0;
        // cout << "Call " << left << endl;
        int lenLeft = lenNum(left);
        if (lenLeft == len) return 1;
        int sub = subNum(maximum, lenLeft);
        if (left < sub) return (pow(10, len - lenLeft + 1) - 1) / 9;
        if (left > sub) return (pow(10, len - lenLeft) - 1) / 9;
        int res = 1;
        for (int i = 0; i < 10; i++){
            res += counting(left*10 + i, maximum, len);
        }
        return res;
    }

    int findKthNumber(int n, int k) {
        int left = 0, lenn = lenNum(n);
        while (k > 0){
            for (int i = 0; i < 10; i++){
                int newLeft = 10*left + i;
                if (newLeft == left) continue;
                int c = counting(newLeft, n, lenn);
                if (k > c) {
                    k -= c;
                } else {
                    left = newLeft;
                    k--;
                    cout << left << endl;
                    break;
                }
            }
        }
        return left;
    }
};
7700