LeetCode 2. 两数相加

Posted by cody1991 on August 2, 2020

简单思路:链表形式的加法运算,我们只要遍历两个链表,记得进位 + 1 就好了

2. 两数相加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */

function ListNode(val) {
  this.val = val;
  this.next = null;
}

var addTwoNumbers = function (l1, l2) {
  const result = new ListNode(0);
  let cur = result;
  let flag = 0;

  while (l1 !== null || l2 !== null || flag) {
    let sum = flag;
    if (l1 !== null) {
      sum += l1.val;
      l1 = l1.next;
    }
    if (l2 !== null) {
      sum += l2.val;
      l2 = l2.next;
    }

    flag = Math.floor(sum / 10);
    sum = sum % 10;
    cur.next = new ListNode(sum);
    cur = cur.next;
  }
  return result.next;
};