leetcode 第二題 兩數相加 java
阿新 • • 發佈:2019-02-07
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list=new ListNode(0);
ListNode current=list;
int x=0;int y=0;
int h=0;
int r=0;
while(l1!=null || l2!=null){
if(l1!=null){
x=l1.val;
l1=l1.next;
}
else x=0;
if(l2!=null){
y=l2.val;
l2=l2.next;
}
else y=0;
int sum=x+y+h;
r=sum%10;
h=sum/10;
current.next=new ListNode(r);
current=current.next;
}
if (h!=0){
current.next=new ListNode(h);
}
return list.next;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list=new ListNode(0);
ListNode current=list;
int x=0;int y=0;
int h=0;
int r=0;
while(l1!=null || l2!=null){
if(l1!=null){
x=l1.val;
l1=l1.next;
}
else x=0;
if(l2!=null){
y=l2.val;
l2=l2.next;
}
else y=0;
int sum=x+y+h;
r=sum%10;
h=sum/10;
current.next=new ListNode(r);
current=current.next;
}
if (h!=0){
current.next=new ListNode(h);
}
return list.next;
}
}