LeetCode No.2

public class ListNode {
int val;
ListNode next;

public ListNode(int val) {
this.val = val;
}
}
class Solution{
public ListNode addTwoNumbers(ListNode l1,ListNode l2){
ListNode pre=new ListNode(0);
ListNode temp=pre;
int carry=0;
while (l1!=null||l2!=null){//当l1,l2都等于null时才跳出
int x=l1==null?0:l1.val;
int y=l2==null?0:l2.val;
int sum=x+y+carry;

carry=sum/10;
sum=sum%10;
temp.next=new ListNode(sum);

temp=temp.next;
if (l1!=null){
l1=l1.next;
}
if (l2!=null){
l2=l2.next;
}
}
if (carry==1){
temp.next=new ListNode(carry);
}
return pre.next;//输出时个位在前
}
}

 

 

 

 

 

 

 

 

 

posted @ 2021-08-06 14:12  朱在春  阅读(22)  评论(0编辑  收藏  举报