共计 728 个字符,预计需要花费 2 分钟才能阅读完成。
You are given two non-empty linked lists representing two non-negativeintegers. The digits are stored in reverse order and each of theirnodes contain a single digit. Add the two numbers and return it as alinked list.You may assume the two numbers do not contain any leading zero, exceptthe number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:342 + 465 = 807.
考察大数相加,注意进位,加法是否完成取决于进位,两个链表任意不为空,循环中这几个条件都不满足才退出这种或的循环一定要注意循环体内有些条件已经不满足
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry=0;
ListNode head=new ListNode(0);
ListNode cur=head;
while(l1!=null || l2!=null || carry>0){
int sum=carry;
if(l1!=null){
sum+=l1.val;
l1=l1.next;
}
if(l2!=null){
sum+=l2.val;
l2=l2.next;
}
if(sum>=10){
sum-=10;
carry=1;
}else carry=0;
cur.next=new ListNode(sum);
cur=cur.next;
}
return head.next;
}