码迷,mamicode.com
首页 > 其他好文 > 详细

2. Add Two Numbers

时间:2017-10-05 23:37:06      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:添加   pre   leading   sts   ati   each   any   view   tno   

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 };

 

2. Add Two Numbers

标签:添加   pre   leading   sts   ati   each   any   view   tno   

原文地址:http://www.cnblogs.com/huenchao/p/7630237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!