<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>

typedef long long int ll;

class Solution {
public:
    int findKthNumber(int N, int k) {

        string ans = "";

        string s = to_string(N);
        
        vector<ll> p10(11, 1);
        vector<ll> cp10( 11, 1);

        for( ll i=1; i<11; i++) {
            p10[i] = 10*p10[i-1];
            cp10[i] = cp10[i-1] + p10[i];
        }

        bool first = true;

        while(k) {

            ll td = s[0]-'0';
            ll dig;
            ll n = s.length();
            
            for( ll d=first; d<10; d++) {
                ll v;
                if(d<td) {
                    v = cp10[n-1];
                } else if(d==td) {
                    v = cp10[n-1] - p10[n-1] + stoi(s) - p10[n-1]*td + 1;
                } else {
                    v = cp10[n-1] - p10[n-1];
                }
                if(v>=k) {
                    dig = d;
                    break;
                }
                k = k - v;
            }

            k = k - 1;
            ans.push_back('0'+dig);

            if(k==0) {
                break;
            }

            if(dig<td) {
                s = string(n-1, '9');
            } else if(dig==td) {
                s = s.substr( 1, n-1);
            } else {
                s = string(n-2, '9');
            }

            first = false;
        }

        return stoi(ans);
    }
};
7600