From a5e3b1140ec34399e172e0405eb99f323e275a24 Mon Sep 17 00:00:00 2001 From: m4siri Date: Sun, 30 Nov 2025 20:47:11 +0545 Subject: lc starting today - 2025-11-30 --- 02_add-two-numbers/src/main.rs | 84 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 02_add-two-numbers/src/main.rs (limited to '02_add-two-numbers/src/main.rs') diff --git a/02_add-two-numbers/src/main.rs b/02_add-two-numbers/src/main.rs new file mode 100644 index 0000000..6b46dbf --- /dev/null +++ b/02_add-two-numbers/src/main.rs @@ -0,0 +1,84 @@ +fn main() { + let list1 = Some(Box::new(ListNode { + val: 2, + next: Some(Box::new(ListNode { + val: 4, + next: Some(Box::new(ListNode { val: 3, next: None })), + })), + })); + + let list2 = Some(Box::new(ListNode { + val: 5, + next: Some(Box::new(ListNode { + val: 6, + next: Some(Box::new(ListNode { val: 4, next: None })), + })), + })); + + Solution::add_two_numbers(list1, list2); +} + +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 add_two_numbers( + l1: Option>, + l2: Option>, + ) -> Option> { + let ans = Self::double_walker(l1, l2, false); + ans + } + + fn double_walker( + l1: Option>, + l2: Option>, + carry: bool, + ) -> Option> { + if let (None, None) = (&l1, &l2) { + if carry { + return Some(Box::new(ListNode::new(1))); + } else { + return None; + } + } + + let mut node = ListNode::new(0); + + if let Some(n1) = &l1 { + node.val += n1.val; + } + + if let Some(n2) = &l2 { + node.val += n2.val; + } + + if carry { + node.val += 1; + } + + node.next = Self::double_walker( + l1.and_then(|n| n.next), + l2.and_then(|n| n.next), + node.val >= 10, + ); + + if node.val >= 10 { + node.val = node.val - 10; + } + + Some(Box::new(node)) + } +} -- cgit v1.2.3