From 4d22e9b4f3bcdb63304fbededc1e6bdd93b6c629 Mon Sep 17 00:00:00 2001 From: Leon Xu <6479451-leonxu260@users.noreply.gitlab.com> Date: Tue, 19 Oct 2021 20:23:05 -0700 Subject: [PATCH] doc: add addTwoNums problem description and solutions to the LeetCode problem --- source/_posts/addTwoNums.md | 59 +++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/source/_posts/addTwoNums.md b/source/_posts/addTwoNums.md index 13afc42..5663879 100644 --- a/source/_posts/addTwoNums.md +++ b/source/_posts/addTwoNums.md @@ -8,3 +8,62 @@ categories: 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; +}; +``` \ No newline at end of file