Skip to content

Commit

Permalink
#20: add solution for exercise #2 in rust
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielvictorcf authored and gosiqueira committed Nov 1, 2022
1 parent 0327a9b commit f79c6e3
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions rust/linked-lists/0002-add-two-numbers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
fn add_lists(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>, carry: i32) -> Option<Box<ListNode>> {
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)
}
}

0 comments on commit f79c6e3

Please sign in to comment.