leetcode

Degree

Medium ★★★ ε=(´ο`*)))

Description

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.

Ideas

  • 给定的数据是链表的形式,相加之后的数据也以链表的形式返回即可
  • 从个位开始相加,生成的数字的个位数就是新数字的个位数,十位数放到下个数中相加。对其他位数执行上述操作。这个小学生都会,那么如何在链表中实现呢?这需要你了解链表几个常用操作:
  • 如何遍历链表?如何生成新链表?
  • 如何遍历链表呢?非常简单,你需要一个 current 指针(其实就是个变量),然后在 while 循环中执行 current = current.next 即可。
  • 如何生成新链表?这也非常简单,你只需要一个 current 指针指向链表最后一位,然后执行 current.next = new Node(val) 即可。
  • 了解了链表的这两个操作,然后我们对前两个链表进行遍历相加,生成新链表即可。为此,我们需要设置几个变量:
    三个链表的 current 指针:c1、c2、c3。
    新链表:l3。
    放到下一位相加的数字:carry。

Code

/**
 * 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) {
    var c1 = l1,
        c2 = l2,
        l3, c3,
        carry = 0;
    while (c1 || c2 || carry) {
        var v1 = 0,
            v2 = 0;

        // 这么做是为了防止整数中当前位上没有数字
        if (c1) {
            v1 = c1.val;
            c1 = c1.next;
        }
        if (c2) {
            v2 = c2.val;
            c2 = c2.next;
        }
        var sum = v1 + v2 + carry;
        carry = Math.floor(sum / 10);
        if (!c3) {
            l3 = new ListNode(sum % 10);
            c3 = l3;
        } else {
            c3.next = new ListNode(sum % 10);
            c3 = c3.next;
        }
    }
    return l3;
};
原文地址:https://www.cnblogs.com/Iris-mao/p/8743694.html