搜索此博客

2012年10月15日星期一

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

Note the carry at the end.
01 public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
02     int carrier=0;
03     int value=0;
04     int sum=0;
05     ListNode head=null;
06     ListNode curr=null;
07     while(l1!=null && l2 !=null)
08     {
09         sum=l1.val+l2.val+carrier;
10         value=sum%10;
11         ListNode temp=new ListNode(value);
12         carrier=sum/10;
13         if(head==null)
14         {
15             head=temp;
16             curr=head;
17         }
18         else
19         {
20             curr.next=temp;
21             curr=curr.next;
22         }
23         l1=l1.next;
24         l2=l2.next;
25     }
26   
27     while(l1!=null)
28     {
29         sum=carrier+l1.val;
30         value=sum%10;
31         ListNode temp=new ListNode(value);
32         carrier=sum/10;
33         curr.next=temp;
34         curr=curr.next;
35         l1=l1.next;
36     }
37     while(l2!=null)
38     {
39         sum=carrier+l2.val;
40         value=sum%10;
41         ListNode temp=new ListNode(value);
42         carrier=sum/10;
43         curr.next=temp;
44         curr=curr.next;
45         l2=l2.next;
46     }
47   
48     if(carrier>0)
49     {
50         ListNode temp=new ListNode(carrier);
51         curr.next=temp;
52         curr=curr.next;
53     }
54   
55     return head;
56 }

没有评论:

发表评论