Question
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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
My Solution
Notice: non-empty list, non-negative integers and stored in reverse order.
Original Solution(Not passed)
Train of thought:
Construct a new linked list to store the sum. For the extra time of instantiating each node, the solution gets Time Limit Exceeded warning.
class MySolution1(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
head.next = ListNode(0)
result = head.next
while l1 is not None:
if l2 is not None:
the_sum = l1.val + l2.val
if the_sum / 10 != 1:
result.val += the_sum
l1 = l1.next
l2 = l2.next
if l1 is not None or l2 is not None:
result.next = ListNode(0)
result = result.next
else:
result.val += the_sum % 10
l1 = l1.next
l2 = l2.next
result.next = ListNode(1)
result = result.next
else:
the_sum = l1.val + result.val
if the_sum != 10:
result.val = the_sum
l1 = l1.next
if l1 is not None:
result.next = ListNode(0)
result = result.next
else:
result.val = 0
result.next = ListNode(1)
result = result.next
while l2 is not None:
the_sum = l2.val + result.val
if the_sum != 10:
result.val = the_sum
l2 = l2.next
if l2 is not None:
result.next = ListNode(0)
result = result.next
else:
result.val = 0
result.next = ListNode(1)
result = result.next
l2 = l2.next
head = head.next
return head
Optimized Solution
Train of thought:
The node is useless after the digit is processed. Based on the idea, we can save more time and space, which means we need to instantiate at most one node(to store the potential carry bit).
class MySolution2(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
head = l1
previous = head
while l1 is not None and l2 is not None:
carry, l1.val = divmod(l1.val + l2.val + carry, 10)
previous = l1
l1 = l1.next
l2 = l2.next
if l1 is None and l2 is None:
if carry == 1:
previous.next = ListNode(1)
return head
while l1 is not None:
carry, l1.val = divmod(l1.val + carry, 10)
if l1.next is not None:
l1 = l1.next
elif carry == 1:
l1.next = ListNode(1)
break
else:
break
if l2 is not None:
previous.next = l2
while l2 is not None:
carry, l2.val = divmod(l2.val + carry, 10)
if l2.next is not None:
l2 = l2.next
elif carry == 1:
l2.next = ListNode(1)
break
else:
break
return head
Editorial Solution of LeetCode
Train of thought:
The idea is just like the first solution of mine. However, the second one is more time-saving and space-saving.