Last active
June 24, 2020 09:27
-
-
Save LarryKarani/fa2b94fcf650a56277810905437d0843 to your computer and use it in GitHub Desktop.
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
# 4 Add two numbers as a linked list | |
class ListNode(object): | |
def __init__(self, x): | |
self.val = x | |
self.next = None | |
class Solution(object): | |
def addTwoNumbers(self, l1, l2): | |
result = ListNode(0) | |
result_tail = result | |
carry = 0 | |
while l1 or l2 or carry: | |
val1 = (l1.val if l1 else 0) | |
val2 = (l2.val if l2 else 0) | |
carry, out = divmod(val1+val2 + carry, 10) | |
result_tail.next = ListNode(out) | |
result_tail = result_tail.next | |
l1 = (l1.next if l1 else None) | |
l2 = (l2.next if l2 else None) | |
return result.next | |
l1 = ListNode(2) | |
l1.next = ListNode(4) | |
l1.next.next = ListNode(3) | |
l2 = ListNode(5) | |
l2.next = ListNode(6) | |
l2.next.next = ListNode(4) | |
result = Solution().addTwoNumbers(l1, l2) | |
while result: | |
print (result.val), | |
result = result.next |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment