diff --git a/2807_insert_greatest_common_divisors_in_linked_list/Cargo.lock b/2807_insert_greatest_common_divisors_in_linked_list/Cargo.lock new file mode 100644 index 0000000..dd94f8c --- /dev/null +++ b/2807_insert_greatest_common_divisors_in_linked_list/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "insert_greatest_common_divisors_in_linked_list" +version = "0.1.0" diff --git a/2807_insert_greatest_common_divisors_in_linked_list/Cargo.toml b/2807_insert_greatest_common_divisors_in_linked_list/Cargo.toml new file mode 100644 index 0000000..e212222 --- /dev/null +++ b/2807_insert_greatest_common_divisors_in_linked_list/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "insert_greatest_common_divisors_in_linked_list" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/2807_insert_greatest_common_divisors_in_linked_list/src/main.rs b/2807_insert_greatest_common_divisors_in_linked_list/src/main.rs new file mode 100644 index 0000000..65121a1 --- /dev/null +++ b/2807_insert_greatest_common_divisors_in_linked_list/src/main.rs @@ -0,0 +1,63 @@ +fn main() { + println!("{}", Solution::gcd(10, 25)); +} + +struct Solution; + +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ListNode { + pub val: i32, + pub next: Option>, +} + +impl ListNode { + #[inline] + fn new(val: i32) -> Self { + ListNode { next: None, val } + } +} + +impl Solution { + pub fn insert_greatest_common_divisors( + mut head: Option>, + ) -> Option> { + let mut current = &mut head; + + while let Some(node) = current { + if let Some(next_node) = &node.next { + let a = node.val; + let b = next_node.val; + let gcd = Solution::gcd(a, b); + + let next = node.next.take(); + node.next = Some(Box::new(ListNode { val: gcd, next })); + + current = &mut node.next.as_mut().unwrap().next; + } else { + break; + } + } + + head + } + + fn gcd(mut a: i32, mut b: i32) -> i32 { + if a > b { + let tmp = a; + a = b; + b = tmp; + } + + loop { + let rem = b % a; + b = a; + a = rem; + + if rem == 0 { + break; + } + } + + b + } +}