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
Output: 7 -> 0 -> 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package leetcode.linkedlist; | |
/** | |
* Solution: Just add from head to rear and consider carry. Process is same to merge two sorted LinkedList | |
* head is single digit. then ten digit, hundred digit. | |
* I was confused by "The digits are stored in reverse order" at first. Don't need to reverse any more. | |
* | |
* @author jeffwan | |
* @date Apr 1, 2014 | |
*/ | |
public class AddTwoNumbers { | |
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { | |
if (l1 == null && l2 == null) { | |
return null; | |
} | |
ListNode dummy = new ListNode(0); | |
ListNode head = dummy; | |
int carry = 0; | |
int sum = 0; | |
while (l1 != null && l2 != null) { | |
sum = l1.val + l2.val + carry; | |
carry = sum / 10; | |
head.next = new ListNode(sum % 10); | |
l1 = l1.next; | |
l2 = l2.next; | |
head = head.next; | |
} | |
while (l1 != null) { | |
sum = l1.val + carry; | |
carry = sum / 10; | |
head.next = new ListNode(sum % 10); | |
l1 = l1.next; | |
head = head.next; | |
} | |
while (l2 != null) { | |
sum = l2.val + carry; | |
carry = sum / 10; | |
head.next = new ListNode(sum % 10); | |
l2 = l2.next; | |
head = head.next; | |
} | |
if (carry != 0) { | |
head.next = new ListNode(carry); | |
} | |
return dummy.next; | |
} | |
// ListNode class | |
public static class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
next = null; | |
} | |
} | |
} |
No comments:
Post a Comment