您的位置:首页 > 其它

[Lintcode] Add Two Numbers I && II

2015-11-17 11:52 323 查看

Add Two Numbers

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
.

SOLUTION:

很简单,就是对应加法,重新见一个linkedlist,然后还要考虑进位,要一个进位count,位数加法还要加上count。

代码:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists2(ListNode l1, ListNode l2) {
if (l1 == null){
return l2;
}
if (l2 == null){
return l1;
}
l1 = reverse(l1);
l2 = reverse(l2);
ListNode head = add(l1, l2);
return reverse(head);
}
private ListNode reverse(ListNode head){
if (head == null){
return null;
}
ListNode pre = null;
while (head != null){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
private ListNode add(ListNode l1, ListNode l2){
if (l1 == null){
return l2;
}
if (l2 == null){
return l1;
}
int sum = 0;
int count = 0;
ListNode dummy = new ListNode(0);
ListNode curr = dummy;
while (l1 != null && l2 != null){
sum = l1.val + l2.val + count;
curr.next = new ListNode(sum % 10);
count = sum / 10;
curr = curr.next;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null){
sum = l1.val + count;
curr.next = new ListNode(sum % 10);
count = sum / 10;
curr = curr.next;
l1 = l1.next;
}
while (l2 != null){
sum = l2.val + count;
curr.next = new ListNode(sum % 10);
count = sum / 10;
curr = curr.next;
l2 = l2.next;
}
if (count != 0){
curr.next = new ListNode(count);
}
return dummy.next;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: