Skip to content

Commit

Permalink
Add problem 2269: Find the K-Beauty of a Number
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jul 3, 2024
1 parent 40d5e7e commit 1859805
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1587,6 +1587,7 @@ pub mod problem_2262_total_appeal_of_a_string;
pub mod problem_2264_largest_3_same_digit_number_in_string;
pub mod problem_2265_count_nodes_equal_to_average_of_subtree;
pub mod problem_2266_count_number_of_texts;
pub mod problem_2269_find_the_k_beauty_of_a_number;
pub mod problem_2270_number_of_ways_to_split_array;

#[cfg(test)]
Expand Down
60 changes: 60 additions & 0 deletions src/problem_2269_find_the_k_beauty_of_a_number/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

use std::num::NonZeroU32;

impl Solution {
pub fn divisor_substrings(num: i32, k: i32) -> i32 {
let num = num as u32;
let mut k = k as u32;
let mut x = num;
let mut base = 1;
let mut window = 0;

loop {
window += base * (x % 10);
x /= 10;
k -= 1;

if k == 0 {
break;
}

base *= 10;
}

let mut result = 0;

loop {
if NonZeroU32::new(window).map_or(false, |window| num % window == 0) {
result += 1;
}

if x == 0 {
break;
}

window = window / 10 + base * (x % 10);
x /= 10;
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn divisor_substrings(num: i32, k: i32) -> i32 {
Self::divisor_substrings(num, k)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
18 changes: 18 additions & 0 deletions src/problem_2269_find_the_k_beauty_of_a_number/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
pub mod iterative;

pub trait Solution {
fn divisor_substrings(num: i32, k: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
let test_cases = [((240, 2), 2), ((430_043, 2), 2)];

for ((num, k), expected) in test_cases {
assert_eq!(S::divisor_substrings(num, k), expected);
}
}
}

0 comments on commit 1859805

Please sign in to comment.