LeetCode #2: Add Two Numbers

Adrian Macal
2 min readJun 17, 2023

--

This time it was a return to the past. The past when I first learned how to add two big numbers together. Unlike those days in school, the numbers here are represented as singly-linked lists.

How simple can a solution be? I didn’t follow the functional approach typical to Rust, but I still find the code quite readable. The main idea behind my approach follows the primary school recipe: add two digits, set the unit digit as the value, and carry over any overflow. A recursive call can handle the rest.

type Node = Option<Box<ListNode>>;

fn add_with_carry(l1: Node, l2: Node, carry: i32) -> Node {
let (v1, n1, b1) = match l1 {
Some(node) => (node.val, node.next, true),
None => (0, None, false),
};

let (v2, n2, b2) = match l2 {
Some(node) => (node.val, node.next, true),
None => (0, None, false),
};

let value = v1 + v2 + carry;

if value > 0 || b1 || b2 {
let mut node = ListNode::new(value % 10);
node.next = add_with_carry(n1, n2, value / 10);
Some(Box::new(node))
} else {
None
}
}

impl Solution {
pub fn add_two_numbers(l1: Node, l2: Node) -> Node {
add_with_carry(l1, l2, 0)
}
}

I continue to be impressed by the difference in performance when comparing submissions in Python vs Rust.

--

--

Adrian Macal
Adrian Macal

Written by Adrian Macal

Software Developer, Data Engineer with solid knowledge of Business Intelligence. Passionate about programming.

No responses yet