diff --git a/440. K-th Smallest in Lexicographical Order1 b/440. K-th Smallest in Lexicographical Order1 new file mode 100644 index 0000000..0440b5c --- /dev/null +++ b/440. K-th Smallest in Lexicographical Order1 @@ -0,0 +1,28 @@ +class Solution { +public: + long countSteps(long prefix, long n) { + long steps = 0, nextPrefix = prefix + 1; + while (prefix <= n) { + steps += min(n + 1, nextPrefix) - prefix; + prefix *= 10; + nextPrefix *= 10; + } + return steps; + } + + int findKthNumber(int n, int k) { + int curr = 1; + k--; + while (k > 0) { + long steps = countSteps(curr, n); + if (steps <= k) { + curr++; + k -= steps; + } else { + curr *= 10; + k--; + } + } + return curr; + } +};