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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution1:遍历对应计算with 进位c
思路: MAINLY: sum += cur1.val + cur2.val + c;
当前结点=sum / 10; c = sum %10
Time Complexity: O(N) Space Complexity: O(1)
Solution2:Early stop version (faster)
Solution1 Code:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur1 = l1;
ListNode cur2 = l2;
ListNode prev = dummy;
int c = 0;
while(cur1 != null || cur2 != null || c != 0) {
int sum = c;
if(cur1 != null) {
sum += cur1.val;
cur1 = cur1.next;
}
if(cur2 != null) {
sum += cur2.val;
cur2 = cur2.next;
}
ListNode node = new ListNode(sum % 10);
c = sum / 10;
prev.next = node;
prev = node;
}
return dummy.next;
}
}
Solution2 Code:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
int c = 0;
while(l1 != null && l2 != null) {
int sum = c;
sum += l1.val;
sum += l2.val;
ListNode node = new ListNode(sum % 10);
c = sum / 10;
cur.next = node;
cur = cur.next;
l1 = l1.next;
l2 = l2.next;
}
while(c != 0) {
int sum = c;
if(l1 != null) sum += l1.val;
if(l2 != null) sum += l2.val;
ListNode node = new ListNode(sum % 10);
c = sum / 10;
cur.next = node;
cur = cur.next;
if(l1 != null) l1 = l1.next;
if(l2 != null) l2 = l2.next;
}
if(l1 != null) cur.next = l1;
else if(l2 != null) cur.next = l2;
return dummy.next;
}
}