English: leetcode-cn.com/problems/ad…
English: leetcode.com/problems/ad…
Topic describes
Give two non-empty linked lists to represent two non-negative integers. Their respective bits are stored in reverse order, and each node can store only one digit.
If we add these two numbers together, a new linked list is returned to represent their sum.
You can assume that neither of these numbers will start with 0, except for the number 0.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Cause: 342 + 465 = 807Copy the code
Answer key
First of all, if you add each digit, you’re going to get a carry, which we’ll call carry. The most that can be carried is 1, because the most that can be done is 9 + 9 + 1 = 19, which is to add the two largest numbers and add the digits, so that the most that can be carried is 19, and there is no carry 2.
/**
* 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) {// Assign p and q to the ones bits of the heads of the given two lists l1 and L2, respectivelylet p = l1
letQ = l2 // Initialize carry to 0letCarry = 0 // Initializes a node's head, dummy head, which does not store numbers. Const dummyHead = new ListNode()letCurr = dummyHead // loop until p and q are both null and exit the loopwhile(p | | q) {/ / set the value of x for p nodes, if p is null, set to 0 x / / set the value of y is q node, if q is null, set to 0 const y x = p? p.val : 0 const y = q ? q.val : // Set sum = x + y + carry const sum = x + y + carry // update carry = sum / 10 carry = math.floor (sum / 10) // create a value of sum Next = new ListNode(sum % 10); next = new ListNode(sum % 10); curr = curr.next; // Move p and q forwardif (p) p = p.next
if(q) q = q.ext} // Determine whether carry is equal to 1. If it is equal to 1, add a node of 1 to the end of the listif(carry > 0) { curr.next = new ListNode(carry); } // returns dummy head's next, where the units digit beginsreturn dummyHead.next
};
function ListNode(val) {
this.val = val;
this.next = null;
}
// [2,4,3]
// [5,6,4]
let l1 = new ListNode(2)
l1.next = new ListNode(4)
l1.next.next = new ListNode(3)
l1.next.next.next = null
let l2 = new ListNode(5)
l2.next = new ListNode(6)
l2.next.next = new ListNode(4)
l2.next.next.next = null
console.log(addTwoNumbers(l1, l2))
Copy the code