From f79c6e3fe87aea4509758fefd5c12b7537c19e23 Mon Sep 17 00:00:00 2001 From: gabrielvictorcf Date: Mon, 31 Oct 2022 23:36:48 -0300 Subject: [PATCH] #20: add solution for exercise #002 in rust --- rust/linked-lists/0002-add-two-numbers.rs | 45 +++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 rust/linked-lists/0002-add-two-numbers.rs diff --git a/rust/linked-lists/0002-add-two-numbers.rs b/rust/linked-lists/0002-add-two-numbers.rs new file mode 100644 index 0000000..b00dc78 --- /dev/null +++ b/rust/linked-lists/0002-add-two-numbers.rs @@ -0,0 +1,45 @@ +// Definition for singly-linked list. +// #[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 add_two_numbers(l1: Option>, l2: Option>) -> Option> { + fn add_lists(l1: Option>, l2: Option>, carry: i32) -> Option> { + if l1.is_none() && l2.is_none() && carry == 0 { + return None; + } + + let mut val = carry; + val += l1.as_ref().map(|l| l.val).unwrap_or(0); + val += l2.as_ref().map(|l| l.val).unwrap_or(0); + + let mut result = ListNode::new(val%10); + + if l1.is_some() || l2.is_some() { + let nxt = add_lists( + l1.and_then(|l| l.next), + l2.and_then(|l| l.next), + if val > 9 {1} else {0} + ); + + result.next = nxt; + } + + Some(Box::new(result)) + } + + add_lists(l1, l2, 0) + } +} \ No newline at end of file