- 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 = 807
-
function addTwoNums(l1,l2){ var c1 = l1,c2 = l2; var c3,l3,carry=0; while(c1||c2||carry){ var v1 = 0,v2 = 0; if(c1){ v1 = c1.val; c1 = c1.next; } if(c2){ v2 = c2.val; c2 = c2.next; } var sum = v1 + v2 +carry; carry = Math.floor(sum/10); if(! c3){ l3 = new ListNode(sum%10); c3 = l3; }else{ c3.next = new ListNode(sum%10); c3 = c3.next; }}returnl3; }functionListNode(val) { this.val = val; this.next = null; }var a = { val: 2, next: { val: 4, next: { val: 3, next: null } }}; var b = { val: 5, next: { val: 6, next: { val: 4, next: null } }}; console.log(addTwoNums(a,b));Copy the code