--- title: LeetCode刷题:addTwoNums date: 2021-10-19 18:58:14 tags: - LeetCode categories: - LeetCode description: LeetCode addTwoNums题 cover: https://upload.wikimedia.org/wikipedia/commons/0/0a/LeetCode_Logo_black_with_text.svg --- 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. ```javascript const addTwoNumbers = function (l1, l2) { let node = null; const carry = arguments[2]; if (l1 || l2) { const val1 = l1 ? l1.val : 0; const val2 = l2 ? l2.val : 0; const next1 = l1 ? l1.next : null; const next2 = l2 ? l2.next : null; const val = carry ? val1 + val2 + 1 : val1 + val2; node = new ListNode(val % 10); node.next = addTwoNumbers(next1, next2, val >= 10); } else if (carry) { node = new ListNode(1); node.next = null; } return node; }; ``` ```javascript let addTwoNumbers = function (l1, l2) { let sum = 0; let current = new ListNode(0); let result = current; while (l1 || l2) { if (l1) { sum += l1.val; l1 = l1.next; } if (l2) { sum += l2.val; l2 = l2.next; } current.next = new ListNode(sum % 10); current = current.next; sum = sum > 9 ? 1 : 0; } if (sum) { current.next = new ListNode(sum); } return result.next; }; ```