You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their
nodes contain a single digit. Add the two numbers and return it as a
linked list.You may assume the two numbers do not contain any leading zero, except
the number 0 itself.nodeExample:git
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation:
342 + 465 = 807.code
考察大數相加,注意進位,加法是否完成取決於進位,兩個鏈表任意不爲空,循環中這幾個條件都不知足才退出
這種或的循環必定要注意循環體內有些條件已經不知足it
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; }