diff options
Diffstat (limited to 'add-two-numbers')
-rw-r--r-- | add-two-numbers/Cargo.toml | 8 | ||||
-rw-r--r-- | add-two-numbers/src/main.rs | 46 |
2 files changed, 54 insertions, 0 deletions
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<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)) + } +} + |