Skip to main content

Add Two Numbers

算是数据结构题?按位加就行,Rust 可以写出比较优美的状态机 On & O1

// 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//     }//   }// }impl Solution {    pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {        let mut res = None;        let mut current = &mut res;
        let mut t = (&l1, &l2, 0, 0);        loop {            t = match t {                (Some(p), Some(q), res, carry) =>                     (&p.next, &q.next, (p.val + q.val + carry)% 10, (p.val + q.val + carry)/ 10),                (None, Some(q), res, carry) =>                    (&None, &q.next, (q.val + carry)% 10, (q.val + carry)/ 10),                (Some(p), None, res, carry) =>                    (&p.next, &None, (p.val + carry)% 10, (p.val + carry)/ 10),                (None, None, res, carry) if carry == 1 =>                    (&None, &None, 1, 0),                (None, None, res, _) => break            };            *current = Some(Box::new(ListNode::new(t.2)));            current = &mut current.as_mut().unwrap().next;        }
        res    }}