From 6d9aecd427eca26ef23ee706aa2a09564446cc1f Mon Sep 17 00:00:00 2001 From: jackfiled Date: Mon, 9 Jun 2025 12:38:42 +0800 Subject: [PATCH] 20250609 finished. --- src/problem/mod.rs | 2 + ..._k_th_smallest_in_lexicographical_order.rs | 56 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 src/problem/p440_k_th_smallest_in_lexicographical_order.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 20f64ff..a3347da 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -700,3 +700,5 @@ mod p2434_using_a_robot_to_print_the_lexicographically_smallest_string; mod p3170_lexicographically_minimum_string_after_removing_stars; mod p386_lexicographical_numbers; + +mod p440_k_th_smallest_in_lexicographical_order; diff --git a/src/problem/p440_k_th_smallest_in_lexicographical_order.rs b/src/problem/p440_k_th_smallest_in_lexicographical_order.rs new file mode 100644 index 0000000..dbaa205 --- /dev/null +++ b/src/problem/p440_k_th_smallest_in_lexicographical_order.rs @@ -0,0 +1,56 @@ +/** + * [440] K-th Smallest in Lexicographical Order + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn find_kth_number(n: i32, mut k: i32) -> i32 { + let mut currrent = 1; + let n = n as i64; + k -= 1; + + while k > 0 { + let steps = Self::calculate_steps(currrent, n); + // If steps <= k, then the number is in the tree of next current (at least). + if steps <= k { + k -= steps; + currrent += 1; + } else { + // The number is in the current tree. + currrent = currrent * 10; + k -= 1; + } + } + + currrent as i32 + } + + /// Calculate the count of number with prefix current. + fn calculate_steps(current: i64, n: i64) -> i32 { + let mut result = 0; + let (mut first, mut last) = (current, current); + + while first <= n { + result += n.min(last) - first + 1; + first = first * 10; + last = last * 10 + 9; + } + + result as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_440() { + assert_eq!(10, Solution::find_kth_number(13, 2)); + assert_eq!(1, Solution::find_kth_number(1, 1)); + } +}