Last Commit: 2024-01-06 17:50:27

views:

Table of Content

2. Add Two Numbers

source: https://leetcode.com/problems/add-two-numbers/

Question

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 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.

思路

这一题的思路其实和415题很相似,只不过一个是基于字符串,一个是基于链表。特别的一点是,这里使用一个dummy head,会更方便的去做,不用考虑一些特殊情况。

var addTwoNumbers = function (l1, l2) {
  let place = 0;
  let crr1 = l1;
  let crr2 = l2;
  let crr = l1;
  while (crr1 || crr2) {
      crr = crr1 || crr2;
      const v = `${(crr1?.val || 0) + (crr2?.val || 0) + place}`;
      if (v.length > 1) {
          place = 1;
          crr.val = ~~v[1];
      } else {
          place = 0;
          crr.val = ~~v[0];
      }
      crr1 = crr1?.next;
      crr2 = crr2?.next;
      crr.next = crr1 || crr2 || null;
  }
  if (place) crr.next = new ListNode(1, null);
  return l1;
};

End

这题的基础应该是链表的遍历,如果熟练的话,这题就不难。