Add Two Numbers
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
https://leetcode.com/problems/add-two-numbers/
链表储存的大数加法。
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} l1 10 * @param {ListNode} l2 11 * @return {ListNode} 12 */ 13 var addTwoNumbers = function(l1, l2) { 14 var carry = 0; 15 var result = new ListNode(-1); 16 var resHead = result; 17 while(l1 !== null || l2 !== null){ 18 var sum = carry; 19 if(l1 !== null){ 20 sum += l1.val; 21 l1 = l1.next; 22 } 23 if(l2 !== null){ 24 sum += l2.val; 25 l2 = l2.next; 26 } 27 28 var node = null; 29 if(sum >= 10){ 30 node = new ListNode(sum - 10); 31 carry = 1; 32 }else{ 33 node = new ListNode(sum); 34 carry = 0; 35 } 36 result.next = node; 37 result = result.next; 38 } 39 if(carry === 1){ 40 result.next = new ListNode(1); 41 } 42 return resHead.next; 43 };