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
错误解法:由于数太长。用int,long存不下,导致结果错误。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1==null) return l2; if(l2==null) return l1; ListNode node1=l1; ListNode node2=l2; int a =0,b=0; int c=1; while(node1!=null) { a+=(c*node1.val); c=c*10; node1=node1.next; } c=1; while(node2!=null){ b+=(c*node2.val); c=c*10; node2=node2.next; } int d=a+b; String res=Integer.toString(d); ListNode l3=new ListNode(0); ListNode node3=l3; for(int i=res.length()-1;i>=0;i--){ node3.val=(int)(res.charAt(i))-(int)('0'); if(i>0){ node3.next=new ListNode(0); node3=node3.next; } } return l3; } }
正确解法。空间效率极差。肯定还有更好的解法,没工夫研究,待续……
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(l1==null) return l2; if(l2==null) return l1; ListNode node1=l1; ListNode node2=l2; List<Integer> list1=new ArrayList<Integer>(); List<Integer> list2=new ArrayList<Integer>(); while(node1!=null) { list1.add(node1.val); node1=node1.next; } while(node2!=null){ list2.add(node2.val); node2=node2.next; } while(list1.size()<list2.size()) list1.add(0); while(list2.size()<list1.size()) list2.add(0); ListNode l3=new ListNode(0); ListNode node3=l3; int tmp=0; for(int i=0;i<list1.size();i++){ int a=list1.get(i)+list2.get(i)+tmp; if(a>=10){ node3.val=a-10; tmp=1; } else{ node3.val=a; tmp=0; } if(i<list1.size()-1){ node3.next=new ListNode(0); node3=node3.next; } } if(tmp==1){ node3.next=new ListNode(tmp); } return l3; } }