add initial data

This commit is contained in:
timeshifter committed 2026-09-04 15:56:45 +02:00
1 parent 048a82b101
commit 51d935d06b
66 files changed
+1329

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "add-two-numbers"
version = "0.1.0"
+6
View File
@@ -0,0 +1,6 @@
[package]
name = "add-two-numbers"
version = "0.1.0"
edition = "2024"
[dependencies]
+77
View File
@@ -0,0 +1,77 @@
fn main() {
let l1 = to_nodes(942);
let l2 = to_nodes(9465);
let result = *add_two_numbers(l1, l2).unwrap();
dbg!(result);
}
fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut l1 = l1;
let mut l2 = l2;
let mut carry = false;
let mut head = None;
let mut tail = &mut head;
while l1.is_some() || l2.is_some() || carry {
let a = l1.as_ref().map_or(0, |n| n.val);
let b = l2.as_ref().map_or(0, |n| n.val);
let addition = a + b + carry as i32;
let node = Box::new(ListNode::new(addition % 10));
carry = addition >= 10;
*tail = Some(node);
tail = &mut tail.as_mut().unwrap().next;
l1 = l1.and_then(|n| n.next);
l2 = l2.and_then(|n| n.next);
}
head
}
/////////////////////////////
// Definition for singly-linked list.
#[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 }
}
}
////////////////////////////////
fn to_nodes(number: i32) -> Option<Box<ListNode>> {
let digits = number
.to_string()
.chars()
.map(|c| c.to_string().parse().unwrap())
.rev()
.collect::<Vec<i32>>();
let mut node = ListNode::new(digits[0]);
for item in digits.iter().skip(1) {
push(&mut node, *item);
}
Some(Box::new(node))
}
fn push(node: &mut ListNode, digit: i32) {
if node.next.is_some() {
push(node.next.as_mut().unwrap(), digit);
} else {
let new = ListNode::new(digit);
node.next = Some(Box::new(new));
}
}