題目
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
按照題目要求求和,注意最高位是否是進位得到的1.
代碼
public class AddTwoNumbers { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode p = dummy; int carry = 0; while (l1 != null && l2 != null) { int sum = carry + l1.val + l2.val; carry = 0; if (sum >= 10) { carry = 1; sum -= 10; } p.next = new ListNode(sum); p = p.next; l1 = l1.next; l2 = l2.next; } if (l1 == null) { l1 = l2; } while (l1 != null) { int sum = carry + l1.val; carry = 0; if (sum >= 10) { carry = 1; sum -= 10; } p.next = new ListNode(sum); p = p.next; l1 = l1.next; } p.next = carry == 1 ? new ListNode(1) : null; return dummy.next; } }