summaryrefslogtreecommitdiff
path: root/02_add-two-numbers/src/main.rs
diff options
context:
space:
mode:
authorm4siri <git@m4siri.com>2025-11-30 20:47:11 +0545
committerm4siri <git@m4siri.com>2025-11-30 20:50:52 +0545
commita5e3b1140ec34399e172e0405eb99f323e275a24 (patch)
treed3b436ed072a86e53d3fae7a2ebdf35a7337f19f /02_add-two-numbers/src/main.rs
lc starting today - 2025-11-30
Diffstat (limited to '02_add-two-numbers/src/main.rs')
-rw-r--r--02_add-two-numbers/src/main.rs84
1 files changed, 84 insertions, 0 deletions
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<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>> {
+ let ans = Self::double_walker(l1, l2, false);
+ ans
+ }
+
+ fn double_walker(
+ l1: Option<Box<ListNode>>,
+ l2: Option<Box<ListNode>>,
+ carry: bool,
+ ) -> Option<Box<ListNode>> {
+ 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))
+ }
+}