两数相加 2. Add Two Numbers 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.
Example:
1 2 3 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
末尾置零法 关键点在于如何处理所给的两个链表长度不一致的情况。
末尾置零法的关键在于将短的链表长度用0补充直到长度和长度链表的长度相等。这样写代码比较简洁。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public ListNode addTwoNumbers (ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0 ); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0 ; while (p != null || q != null ) { int x = (p != null ) ? p.val : 0 ; int y = (q != null ) ? q.val : 0 ; int sum = carry + x + y; carry = sum / 10 ; curr.next = new ListNode(sum % 10 ); curr = curr.next; if (p != null ) p = p.next; if (q != null ) q = q.next; } if (carry > 0 ) { curr.next = new ListNode(carry); } return dummyHead.next; }
链表法 链表法相比于末尾置零法,稍微复杂一点,需要判断l1,l2的长度。
若l1比l2长的话,只需根据l1和进位的情况,判断l1是否要进行修改。如果不需要进行修改,则只需将结果链表的下一个结点指向l1的剩余子链表的第一个结点即可。l2同理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 public ListNode addTwoNumbers (ListNode l1, ListNode l2) { int carry = 0 ; int temp = l1.val + l2.val; if (temp >= 10 ){ temp = temp % 10 ; carry ++; } ListNode l3 = new ListNode(temp); ListNode l4 = l3; while (null != l1.next && null != l2.next){ l1 = l1.next; l2 = l2.next; if (carry == 1 ){ temp = l1.val + l2.val + carry; carry --; } else { temp = l1.val + l2.val; } if (temp >= 10 ){ temp = temp % 10 ; carry ++; } l3.next = new ListNode(temp); l3 = l3.next; } while (null != l1.next){ l1 = l1.next; if (carry == 1 ){ temp = l1.val + carry; if (temp >= 10 ){ temp = temp % 10 ; carry ++; } l3.next = new ListNode(temp); carry --; }else { l3.next = new ListNode(l1.val); l3.next.next = l1.next; break ; } l3 = l3.next; } while (null != l2.next){ l2 = l2.next; if (carry == 1 ){ temp = l2.val + carry; if (temp >= 10 ){ temp = temp % 10 ; carry ++; } l3.next = new ListNode(temp); carry --; }else { l3.next = new ListNode(l2.val); l3.next.next = l2.next; } l3 = l3.next; } if (carry == 1 ){ l3.next = new ListNode(carry); } return l4; }