给定两个用链表表示的整数,每个节点包含一个数位。
这些数位是反向存放的,也就是个位排在链表首部。
编写函数对这两个整数求和,并用链表形式返回结果。
示例:
输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295 输出:2 -> 1 -> 9,即912
部分正确,原因是超过了int的范围:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int n1=0;
int n2=0;
int k=1;
while(l1!=null){
n1=n1+l1.val*k;
k*=10;
l1=l1.next;
}
k=1;
while(l2!=null){
n2=n2+l2.val*k;
k*=10;
l2=l2.next;
}
int n3=n1+n2;
System.out.println(n2);
ListNode ans=new ListNode(0);
ListNode anss=ans;
while(n3>=0){
ans.next=new ListNode(n3%10);
n3/=10;
if(n3==0)n3=-1;
ans=ans.next;
}
return anss.next;
}
}
下面是看了题解改进了的(感谢宫水三叶姐姐):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum=0;
ListNode l=new ListNode(-1);
ListNode ans=l;
while(l1!=null || l2!=null || sum!=0){
if(l1!=null){
sum+=l1.val;
l1=l1.next;
}
if(l2!=null){
sum+=l2.val;
l2=l2.next;
}
l.next=new ListNode(sum%10);
l=l.next;
sum/=10;
}
return ans.next;
}
}