167. Add Two Numbers【LintCode by java】

Description

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

Example

Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8

解题:题目的意思是,给两个链表,倒序表示一个若干位的数。要求返回这两个数的和,并且格式是题中规定的链表,也是倒序。思路很清晰,从头到尾,一位一位地相加,并且用一个数来保存进位。每次相加的时候,都得考虑进位,把进位算在其中。当然,思路越清晰,代码可能看起来就比较笨重。代码如下:

 1 /**
 2  * Definition for ListNode
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 
13 public class Solution {
14     /**
15      * @param l1: the first list
16      * @param l2: the second list
17      * @return: the sum list of l1 and l2 
18      */
19     public ListNode addLists(ListNode l1, ListNode l2) {
20         // write your code here
21         ListNode head = new ListNode(0);
22         ListNode p=head;
23         ListNode p1 = l1;
24         ListNode p2 = l2;
25         int sum = 0;//保存每一位的和
26         int more=0;//保存进位
27         while(p1 != null && p2 != null){
28             sum = p1.val + p2.val+more;
29             more = sum / 10;
30             sum = sum % 10;
31             ListNode temp = new ListNode(sum);
32             p.next = temp;
33             p=p.next;
34             p1 = p1.next;
35             p2 = p2.next;
36         }
37         //如果more不为0
38         sum = 0;
39         while(p1 != null){
40             sum = more + p1.val;
41             more = sum / 10;
42             sum = sum % 10;
43             ListNode temp = new ListNode(sum);
44             p.next = temp;
45             p = p.next;
46             p1 = p1.next;
47         }
48         while(p2 != null){
49             sum = more + p2.val;
50             more = sum / 10;
51             sum = sum % 10;
52             ListNode temp = new ListNode(sum);
53             p.next = temp;
54             p = p.next;
55             p2 = p2.next;
56         }
57         if(more != 0){                //如果more不为0,那么最高位就是前面的进位
58             ListNode temp = new ListNode(more);
59             p.next = temp;
60         }
61         return head.next;
62     }
63 }

代码可能有点冗余,曾尝试改进,但发现还是这样写看起来比较清晰。如有错误,欢迎批评指正。

猜你喜欢

转载自www.cnblogs.com/phdeblog/p/9134604.html