LeetCode两数之和
程序员文章站
2022-07-14 23:37:04
...
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null){
l1=new ListNode(0);
}
if(l2==null){
l2=new ListNode(0);
}
if(l1.next==null&&l2.next==null){
int sum =l1.val+l2.val;
if(sum>9){
ListNode node= new ListNode(sum%10);
node.next=new ListNode(sum/10);
return node;
}else{
return new ListNode(sum);
}
}else{
int sum =l1.val+l2.val;
if(sum>9){
sum = sum-10;
if(l1.next!=null){
l1.next.val++;
}else if(l2.next!=null){
l2.next.val++;
}
}
ListNode node=new ListNode(sum);
node.next=addTwoNumbers(l1.next,l2.next);
return node;
}
}
}