程式語言 - LeetCode - Rust - 2. Add Two Numbers



參考資訊:
https://levelup.gitconnected.com/leetcode-problems-add-two-numbers-6a4045ce146c

題目:


解答:

impl Solution {
    pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut l1_cur = l1;
        let mut l2_cur = l2;
        let mut carry = 0;
        let mut r = Some(Box::new(ListNode::new(0)));
        let mut cur = r.as_mut();

        while l1_cur.is_some() || l2_cur.is_some() {
            let mut sum = carry;

            if let Some(node) = l1_cur {
                sum += node.val;
                l1_cur = node.next;
            }

            if let Some(node) = l2_cur {
                sum += node.val;
                l2_cur = node.next;
            }
            carry = sum / 10;

            if let Some(node) = cur {
                node.next = Some(Box::new(ListNode::new(sum % 10)));
                cur = node.next.as_mut();
            }
        }

        if carry > 0 {
            cur.unwrap().next = Some(Box::new(ListNode::new(1)));
        }
        return r.unwrap().next;
    }
}