aboutsummaryrefslogtreecommitdiff
path: root/other/kth_smallest_lexicographical.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/kth_smallest_lexicographical.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/kth_smallest_lexicographical.cpp')
-rw-r--r--other/kth_smallest_lexicographical.cpp31
1 files changed, 31 insertions, 0 deletions
diff --git a/other/kth_smallest_lexicographical.cpp b/other/kth_smallest_lexicographical.cpp
new file mode 100644
index 0000000..71478e9
--- /dev/null
+++ b/other/kth_smallest_lexicographical.cpp
@@ -0,0 +1,31 @@
+// 440. K-th Smallest in Lexicographical Order
+#include "leetcode.h"
+// given two integers 'n' and 'k', return the k'th lexicographically smallest
+// integer
+
+class Soltuion {
+public:
+ int findKthNumber(int n, int k) {
+ int curr = 1;
+ for (--k; k > 0;) {
+ int cnt = 0;
+ for (long long first = static_cast<long long>(curr), last = first + 1;
+ first <= n; first *= 10, last *= 10)
+ cnt += static_cast<int>((min(n + 1LL, last) - first));
+ if (k >= cnt) {
+ ++curr;
+ k -= cnt;
+ } else {
+ curr *= 10;
+ --k;
+ }
+ }
+ return curr;
+ }
+};
+
+int main() {
+ Soltuion obj;
+ printf("%d\n", obj.findKthNumber(13, 2)); // expect: 10
+ printf("%d\n", obj.findKthNumber(1, 1)); // expect: 1
+}