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
Show Similar Problems
Have you met this question in a real interview?
Yes
No
原题地址:https://leetcode.com/problems/add-two-numbers/
第一眼看上去,这不就是一个atoi和一个itoa就可以解决了么。简单又粗暴。
if(l1 == null || l1.next == null){
return l2;
}
if(l2 == null || l2.next == null){
return l1;
}
ListNode Total = new ListNode(0);
ListNode TotalHead = Total;
//int divide = 10;
long ltoi = 1;
long ltoi2 = 1;
long L1 = 0;
long L2 = 0;
while(l1 != null){
L1 += l1.val*ltoi;
l1 = l1.next;
ltoi = ltoi*10;
}
//System.out.print(L1);
while(l2 != null){
L2 += l2.val*ltoi2;
l2 = l2.next;
ltoi2 = ltoi2*10;
}
//System.out.print(L2);
long total = L1 + L2;
//System.out.print(total);
while(total > 0){
Total.next = new ListNode((int)(total%10));
Total = Total.next;
total = total/10;
}
Total = null;
return TotalHead.next;
后来提交的时候才发现自己naive了。虽然我用了一个long整形但是有一个测试用例是9999999999999999999999999999999999999 - -。血崩
只好重新思考。想法是每一个l1,l2的节点值相加,不超过10保存到新的链表中,超过10的话下一个链表节点值+1来模拟进位。但是要考虑一个情况就是进位之后l1或者l2的next可能为空,需要重新增加一个节点避免访问空节点报错。
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) {
if(l1 == null && l2 == null){
return null;
}
ListNode addList = new ListNode(0);
ListNode addListHelper = addList;
while(l1 != null && l2 != null){
int a = l1.val + l2.val;
if( a >= 10){
addList.next = new ListNode(a%10);
if(l1.next == null){
l1.next = new ListNode(1);
}
else{
l1.next.val += 1;
}
}
else{
addList.next = new ListNode(a);
}
l1 = l1.next;
l2 = l2.next;
addList = addList.next;
}
while(l1 != null){
addList.next = new ListNode(l1.val);
addList = addList.next;
l1 = l1.next;
}
while(l2 != null){
addList.next = new ListNode(l2.val);
addList = addList.next;
l2 = l2.next;
}
return addListHelper.next;
/*if(l1 == null || l1.next == null){
return l2;
}
if(l2 == null || l2.next == null){
return l1;
}
ListNode Total = new ListNode(0);
ListNode TotalHead = Total;
//int divide = 10;
long ltoi = 1;
long ltoi2 = 1;
long L1 = 0;
long L2 = 0;
while(l1 != null){
L1 += l1.val*ltoi;
l1 = l1.next;
ltoi = ltoi*10;
}
//System.out.print(L1);
while(l2 != null){
L2 += l2.val*ltoi2;
l2 = l2.next;
ltoi2 = ltoi2*10;
}
//System.out.print(L2);
long total = L1 + L2;
//System.out.print(total);
while(total > 0){
Total.next = new ListNode((int)(total%10));
Total = Total.next;
total = total/10;
}
Total = null;
return TotalHead.next;*/
}
}