summaryrefslogtreecommitdiff
path: root/add-two-numbers/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to 'add-two-numbers/src/main.rs')
-rw-r--r--add-two-numbers/src/main.rs46
1 files changed, 46 insertions, 0 deletions
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))
+ }
+}
+