菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
0
0

用 Rust 刷 leetcode 第二题

原创
05/13 14:22
阅读数 293

Problem

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Explanation: 342 + 465 = 807.

Solution

pub fn reverse_list(node: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
    let mut s = node;
    let mut e = None;
    while let Some(mut n) = s.take() {
        s = n.next;
        n.next = e;
        e = Some(n);
    } 
    e
}

impl Solution {
    pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut l1_curr = l1;
        let mut l2_curr = l2;
        let mut carry = 0;
        let mut result = None;
        while l1_curr.is_some() || l2_curr.is_some() || carry > 0{
            let mut sum = carry;
            if let Some(n) = l1_curr {
                sum += n.val;
                l1_curr = n.next;
            }
            if let Some(n) = l2_curr {
                sum += n.val;
                l2_curr = n.next;
            }
            carry = sum/10;
            let mut node = ListNode::new(sum%10);
            node.next = result;
            result = Some(Box::new(node));
        }
        reverse_list(result)
    }
}

发表评论

0/200
0 点赞
0 评论
收藏