Skip to content

Instantly share code, notes, and snippets.

@purplecandy
Created January 28, 2020 13:51
Show Gist options
  • Save purplecandy/e227af66d57b9eff92f730f160f032dc to your computer and use it in GitHub Desktop.
Save purplecandy/e227af66d57b9eff92f730f160f032dc to your computer and use it in GitHub Desktop.
LeetCode: Add Two Numbers
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# traversing both nodes together and adding the last digit if carry is generated
pnode = result = ListNode(None)
carry = 0
while l1 or l2 or carry:
# in certain cases carry is remian but nodes are traversed
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
pnode.next = ListNode(carry%10)
pnode = pnode.next
# if the carry was > 10 then it will return the 10's digit
# else carry will get set to zero because it has been already utilized
carry //= 10
return result.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment