summaryrefslogtreecommitdiff
path: root/add-two-numbers/src/main.rs
blob: 3a9abe9dabb4507c5af4b4f45e667c95faa91eb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
fn main() {
    println!("Hello, world!");
}

#[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
    }
  }
}
// Comprehensive 3ms Recursive 

struct Solution {}
impl Default for ListNode {
    fn default() -> Self {
        ListNode::new(0)
    }
}

impl Solution {
    pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        Solution::add_two_numbers_with_carry(l1, l2, 0)
    }
    pub fn add_two_numbers_with_carry(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 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))
    }
}