From 4b0a6a01b051a4ebfbc17661d14cb23fe4f275fb Mon Sep 17 00:00:00 2001 From: Orangerot Date: Thu, 27 Jun 2024 11:30:16 +0200 Subject: Initial commit --- add-two-numbers/Cargo.toml | 8 ++++++++ add-two-numbers/src/main.rs | 46 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 add-two-numbers/Cargo.toml create mode 100644 add-two-numbers/src/main.rs (limited to 'add-two-numbers') diff --git a/add-two-numbers/Cargo.toml b/add-two-numbers/Cargo.toml new file mode 100644 index 0000000..eee98ac --- /dev/null +++ b/add-two-numbers/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "add-two-numbers" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/add-two-numbers/src/main.rs b/add-two-numbers/src/main.rs new file mode 100644 index 0000000..3a9abe9 --- /dev/null +++ b/add-two-numbers/src/main.rs @@ -0,0 +1,46 @@ +fn main() { + println!("Hello, world!"); +} + +#[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 + } + } +} +// Comprehensive 3ms Recursive + +struct Solution {} +impl Default for ListNode { + fn default() -> Self { + ListNode::new(0) + } +} + +impl Solution { + pub fn add_two_numbers(l1: Option>, l2: Option>) -> Option> { + Solution::add_two_numbers_with_carry(l1, l2, 0) + } + pub fn add_two_numbers_with_carry(l1: Option>, l2: Option>, carry: i32) -> Option> { + if l1.is_none() && l2.is_none() && carry == 0 {return None;} + let a = l1.unwrap_or_default(); + let b = l2.unwrap_or_default(); + let sum = a.val + b.val + carry; + + let result = ListNode { + val: sum % 10, + next: Solution::add_two_numbers_with_carry(a.next, b.next, sum / 10) + }; + Some(Box::new(result)) + } +} + -- cgit v1.2.3