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.
我的解法是先将两个链表中的数字加到 sum 里,再将 sum 转化成链表。但是如果输入的链表代表的数字如果很大,超过 int 的范围,造成 overflow,那么就会出问题。
因此,应该一位一位实现加法,直接生成新的链表。
/**
* 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 addLists(ListNode l1, ListNode l2) {
// write your code here
if (l1 == null && l2 == null) {
return null;
}
int sum = 0;
int multiplier = 1;
if (l1 != null) {
ListNode temp = l1;
while (temp != null) {
sum += multiplier * temp.val;
multiplier*=10;
temp = temp.next;
}
}
if (l2 != null) {
multiplier = 1;
ListNode temp = l2;
while (temp != null) {
sum += multiplier * temp.val;
multiplier *= 10;
temp = temp.next;
}
}
ListNode head = new ListNode(0);
ListNode tempNode = head;
do {
int value = sum % 10;
tempNode.next = new ListNode(value);
sum = sum / 10;
tempNode = tempNode.next;
}while (sum != 0);
tempNode.next = null;
return head.next;
}
}
九章算法 solution:
public class Solution {
public ListNode addLists(ListNode l1, ListNode l2) {
if(l1 == null && l2 == null) {
return null;
}
ListNode head = new ListNode(0);
ListNode point = head;
int carry = 0;
while(l1 != null && l2!=null){
int sum = carry + l1.val + l2.val;
point.next = new ListNode(sum % 10);
carry = sum / 10;
l1 = l1.next;
l2 = l2.next;
point = point.next;
}
while(l1 != null) {
int sum = carry + l1.val;
point.next = new ListNode(sum % 10);
carry = sum /10;
l1 = l1.next;
point = point.next;
}
while(l2 != null) {
int sum = carry + l2.val;
point.next = new ListNode(sum % 10);
carry = sum /10;
l2 = l2.next;
point = point.next;
}
if (carry != 0) {
point.next = new ListNode(carry);
}
return head.next;
}
}