[路飞]_每天刷leetcode_60( 两数相加 II )

133 阅读2分钟

「这是我参与2022首次更文挑战的第19天,活动详情查看:2022首次更文挑战

两数相加 II Add Two Numbers II

LeetCode传送门445. 两数相加 II

题目

给你两个 非空 链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储一位数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Pasted image 20220130181924.png

Example:

Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]

Input: l1 = [0], l2 = [0]
Output: [0]

Constraints:

  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.

思考线


解题思路

这道题是用链表来做加法,我想到的是,先把链表的值存到数组中,然后使用栈pop方法,从后向前来计算结果。

存放到数组中这个比较好操作,那如何计算呢?

我们找比较长的数组来进行遍历,然后设参数carry来表示进位,默认值为0.

每次我们计算pop后的l1l2的和,同时加上carry的结果,设为r

然后把r%10作为当前位的结果放入res数组中,同时设置carry = Math.floor(r/10);

循环结束后,我们的工作还没完成,我们需要判断一下此时的carry是否为0,若不为0,我们需要再执行结果数组res,让res加入carry的值。

最后我们再把res的值,从后向前转化为链表即可。

有了以上思路,我们的代码实现如下

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function (l1, l2) {
    const arr1 = [];
    const arr2 = []
    while (l1) {
        arr1.push(l1);
        l1 = l1.next;
    }
    while (l2) {
        arr2.push(l2);
        l2 = l2.next;
    }
    let carry = 0;
    let max = Math.max(arr1.length, arr2.length);
    const res = [];
    while (max--) {
        const { val: r1 } = arr1.pop() || {};
        const { val: r2 } = arr2.pop() || {};
        console.log(r1, r2)
        let r;
        if (r1 !== undefined && r2 !== undefined) {
            r = r1 + r2 + carry;

        } else {
            r = r1 === undefined ? r2 + carry : r1 + carry;
        }
        res.push(r % 10);
        carry = Math.floor(r / 10);
    }
    if (carry !== 0) res.push(1)
    let dummyHead = new ListNode(0);
    let reslist = dummyHead;
    while (res.length) {
        reslist.next = new ListNode(res.pop());
        reslist = reslist.next;
    }
    return dummyHead.next;


};

时间复杂度

O(n): n为最长链表的长度

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。