代码:
class Solution { public: long long get_prefix(long long prefix, long long n){ long long x = prefix; long long y = prefix + 1; long long sum = 0; while(x <= n) { sum += min(n+1, y) - x; x *= 10; y *= 10; } return sum; } long long findKthNumber(int n, int k) { long long pos = 1; //指针所在的位置 long long prefix = 1; while(pos < k) { long long num = get_prefix(prefix, n); //统计以prefix为前缀,小于等于 n 的所有数的和 if (num + pos > k) { prefix *= 10; pos++; //此处相当于10叉树向下走一个位置,所以当前位置要加1 } else { pos += num; prefix++; } // printf("prefix = %d pos = %d ", prefix, pos); } // int num = get_prefix(prefix, n); return prefix; } };