Skip to content

Instantly share code, notes, and snippets.

@aadimator
Created September 19, 2018 11:26
Show Gist options
  • Save aadimator/01eee7c74283a6b67baf9a3a86656d49 to your computer and use it in GitHub Desktop.
Save aadimator/01eee7c74283a6b67baf9a3a86656d49 to your computer and use it in GitHub Desktop.
2. Add Two Numbers - LeetCode
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 or not l2: return l1 or l2
resultNode = ListNode(0)
currentNode = resultNode
carry = 0
while l1 or l2:
sum = carry;
if (l1):
sum += l1.val
l1 = l1.next
if (l2):
sum += l2.val
l2 = l2.next
currentNode.next = ListNode(sum % 10)
currentNode = currentNode.next
carry = sum / 10
if carry: currentNode.next = ListNode(carry)
return resultNode.next
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment