You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
【解析】这道题考察链表的使用,难度不大。主要不要忘记最后一个进位。如果sumNode.val=(l1.val+l2.val+进位);进位=(l1.val+l2.val+进位)/10。然后再考虑最后一个进位即可。具体代码如下:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int sum = 0; int carry = 0; ListNode head = null; ListNode l3 = null; while (l1 != null && l2 != null) { sum = (l1.val + l2.val + carry) % 10; carry = (l1.val + l2.val + carry) / 10; ListNode sumNode = new ListNode(sum); if (head == null) head = sumNode; else l3.next = sumNode; l3 = sumNode; l1 = l1.next; l2 = l2.next; } while (l1 != null) { sum = (l1.val + carry) % 10; carry = (l1.val + carry) / 10; ListNode sumNode = new ListNode(sum); if (head == null) head = sumNode; else l3.next = sumNode; l3 = sumNode; l1 = l1.next; } while (l2 != null) { sum = (l2.val + carry) % 10; carry = (l2.val + carry) / 10; ListNode sumNode = new ListNode(sum); if (head == null) head = sumNode; else l3.next = sumNode; l2 = l2.next; l3 = sumNode; } if (carry == 1) { ListNode carryNode = new ListNode(carry); l3.next = carryNode; } return head; } }
