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

2. Add Two Numbers

时间:2016-05-10 23:11:27      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

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

代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
11         int c=0;
12        
13         ListNode a=l1,b=l2;
14         while(a!=null&&b!=null)
15         {a=a.next;b=b.next;}
16         if(b!=null)
17         {
18             ListNode temp=l2;
19             l2=l1;
20             l1=temp;
21         }
22          ListNode l3=l1;
23         while(l1.next!=null&&l2.next!=null)
24         {
25             if(l1.val+l2.val+c>=10)
26             {l1.val=l1.val+l2.val+c-10;
27             c=1;}
28             else 
29             {
30             l1.val=l1.val+l2.val+c;
31             c=0;}
32             
33             l1=l1.next;
34             l2=l2.next;
35         }
36         
37          if(l1.val+l2.val+c>=10)
38             {l1.val=l1.val+l2.val+c-10;
39             c=1;
40             }
41             else 
42             {
43             l1.val=l1.val+l2.val+c;
44             c=0;
45             }
46             
47             try{
48         while(l1.next!=null)
49         {
50             l1=l1.next;
51             if(l1!=null){
52                 if(l1.val+c>=10)
53             {l1.val=l1.val+c-10;c=1;}
54             else
55             {l1.val=l1.val+c;c=0;}
56             
57             }
58         }
59        
60         if(c==1)
61         { ListNode n = new ListNode(1);
62         l1.next = n;}
63  
64             }catch(NullPointerException e){}
65         return l3;
66         
67     }
68 }

 

2. Add Two Numbers

标签:

原文地址:http://www.cnblogs.com/ghuosaao/p/5479632.html

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