Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

445. Add Two Numbers II #112

Open
Tcdian opened this issue Apr 14, 2020 · 1 comment
Open

445. Add Two Numbers II #112

Tcdian opened this issue Apr 14, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 14, 2020

445. Add Two Numbers II

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

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

Example

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7

Follow up

  • 如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 14, 2020

Solution

  • JavaScript Solution
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    const stack1 = [];
    const stack2 = [];
    let carry = 0;
    let result = null;

    while (l1 !== null) {
        stack1.push(l1.val);
        l1 = l1.next;
    }
    while (l2 !== null) {
        stack2.push(l2.val);
        l2 = l2.next;
    }

    while (stack1.length !== 0 || stack2.length !== 0 || carry !== 0) {
        const v1 = stack1.pop() || 0;
        const v2 = stack2.pop() || 0;
        const current = (v1 + v2 + carry) % 10;
        const currentNode = new ListNode(current);
        currentNode.next = result;
        result = currentNode;
        carry = Math.floor((v1 + v2 + carry) / 10);
    }

    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant