1use crate::ListNode;
21
22pub struct Solution;
24
25impl Solution {
26 pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
27 let mut result = None;
28 let mut tail = &mut result;
29 let mut t = (l1, l2, 0, 0); loop {
31 t = match t {
32 (None, None, _, 0) => break,
33 (None, None, _, carry) => (None, None, carry, 0),
34 (Some(list), None, _, carry) | (None, Some(list), _, carry) if list.val + carry >= 10 => {
35 (list.next, None, list.val + carry - 10, 1)
36 }
37 (Some(list), None, _, carry) | (None, Some(list), _, carry) => {
38 (list.next, None, list.val + carry, 0)
39 }
40 (Some(l1), Some(l2), _, carry) if l1.val + l2.val + carry >= 10 => {
41 (l1.next, l2.next, l1.val + l2.val + carry - 10, 1)
42 }
43 (Some(l1), Some(l2), _, carry) => {
44 (l1.next, l2.next, l1.val + l2.val + carry, 0)
45 }
46 };
47
48 *tail = Some(Box::new(ListNode::new(t.2)));
49 tail = &mut tail.as_mut().unwrap().next;
50 }
51 result
52 }
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58 use crate::list;
59
60 #[test]
61 fn test() {
62 let cases = vec![
63 (vec![], (list![], list![])),
64 (vec![7,0,8], (list![7,0,8], list![])),
65 (vec![7,0,8], (list![], list![7,0,8])),
66 (vec![7,0,8], (list![2,4,3], list![5,6,4])),
67 (vec![2,1,9], (list![7,1,6], list![5,9,2])),
68 (vec![2,1,1,1], (list![7,1,6], list![5,9,4])),
69 ];
70
71 for (expect, (l1, l2)) in cases {
72 assert_eq!(expect, ListNode::into_vec(Solution::add_two_numbers(l1, l2)));
73 }
74 }
75}