167 · Add Two Numbers - LintCode
# Description
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse
order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Example 1:
Input: 7->1->6->null, 5->9->2->null
Output: 2->1->9->null
Explanation: 617 + 295 = 912, 912 to list: 2->1->9->null
Example 2:
Input: 3->1->5->null, 5->9->2->null
Output: 8->0->8->null
Explanation: 513 + 295 = 808, 808 to list: 8->0->8->null
# Solution
/** | |
* Definition for ListNode | |
* public class ListNode { | |
* int val; | |
* ListNode next; | |
* ListNode(int x) { | |
* val = x; | |
* next = null; | |
* } | |
* } | |
*/ | |
public class Solution { | |
/** | |
* @param l1: the first list | |
* @param l2: the second list | |
* @return: the sum list of l1 and l2 | |
*/ | |
public ListNode addLists(ListNode l1, ListNode l2) { | |
if (l1 == null || l2 == null){ | |
return null; | |
} | |
ListNode head = new ListNode(0); | |
ListNode point = head; | |
int carry = 0; | |
while (l1 != null && l2 != null){ | |
int sum = carry + l1.val + l2.val; | |
point.next = new ListNode(sum % 10); //12%10 記 2 | |
carry = sum / 10; //carry = 1; | |
point = point.next; | |
l1 = l1.next; | |
l2 = l2.next; | |
} | |
while (l2 != null){ | |
int sum = carry + l2.val; | |
point.next = new ListNode(sum % 10); | |
carry = sum / 10; //carry = 1; | |
point = point.next; | |
l2 = l2.next; | |
} | |
while (l1 != null){ | |
int sum = carry + l1.val; | |
point.next = new ListNode(sum % 10); | |
carry = sum / 10; //carry = 1; | |
point = point.next; | |
l1 = l1.next; | |
} | |
if (carry != 0) { | |
point.next = new ListNode(carry); | |
} | |
return head.next; | |
} | |
} |