2. Add Two Numbers

2. Add Two Numbers

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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

 

 

 
 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     
15     //这种累加的题目,主要是注意进位
16     var carry = 0;
17     //头指针
18     var head = new ListNode(0);
19 
20     var res = head;
21     
22     //保证两个都有值 就累加,否者就直接添加
23     while(l1&&l2){
24         
25         //一开始就加上carry,默认是0
26         var val = l1.val + l2.val + carry;
27         val - 9 > 0 ? carry = 1 : carry = 0;
28      
29         val %= 10;  
30         var node = new ListNode(val);
31         res.next = node;
32         
33         res = node;
34         
35         l1 = l1.next;
36         l2 = l2.next;
37        
38     }
39     
40     //处理 2->3->4 + 2->3 这种
41     while(l1){
42      
43             var val = l1.val + carry;
44             val - 9 > 0 ? carry = 1 : carry = 0;
45             val %= 10;
46             var node = new ListNode(val);
47             res.next = node;
48         
49             res = node;
50             l1 = l1.next;
51      
52     }
53     
54      while(l2){
55      
56             var val = l2.val + carry;
57             val - 9 > 0 ? carry = 1 : carry = 0;
58             val %= 10;
59             var node = new ListNode(val);
60             res.next = node;
61         
62             res = node;
63             l2 = l2.next;
64     }
65     
66     //注意处理最后一个进位  比如 5,5  输出0->1
67     if(carry){
68            var node = new ListNode(carry);
69             res.next = node;
70 
71             res = node;
72     }
73     
74     return head.next;
75     
76     
77 };

 

posted @ 2017-10-05 23:03  hdu胡恩超  阅读(176)  评论(0编辑  收藏  举报