From 56c767a65aecdb33ae3210eba1034586dd249e9e Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Thu, 24 Mar 2022 20:13:01 +0800 Subject: [PATCH] add: 220323-CN [cpp] --- cpp/2203/220323-CN.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 cpp/2203/220323-CN.cpp diff --git a/cpp/2203/220323-CN.cpp b/cpp/2203/220323-CN.cpp new file mode 100644 index 0000000..6586d68 --- /dev/null +++ b/cpp/2203/220323-CN.cpp @@ -0,0 +1,31 @@ +#include + +/** + * 440. K-th Smallest in Lexicographical Order + * Given two integers n and k, return the kth lexicographically smallest integer in the range [1, n]. + */ + +class Solution { +public: + int findKthNumber(int n, int k) { + auto getCount = [&](int prefix, unsigned long long n) { + auto count = 0ULL; + for (unsigned long long cur = prefix, next = prefix + 1; cur <= n; cur *= 10, next *= 10) + count += std::min(next, n + 1) - cur; + return count; + }; + auto p = 1; + auto prefix = 1; + while (p < k) { + auto count = getCount(prefix, n); + if (p + count > k) { + prefix *= 10; + p++; + } else if (p + count <= k) { + prefix++; + p += count; + } + } + return prefix; + } +}; \ No newline at end of file