# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
dummy=ListNode(None)
tail=dummy
carry=0
while l1 or l2 or carry:
v1=l1.val if l1 else 0 # there might be a case where 2 digit
v2=l2.val if l2 else 0 # number is add with 3 so we add 0
"""1-->2-->9
2-->3-->2-->1 in above we place 0 """
val=v1+v2+carry
carry=val//10 # it stores 10th place in carry
val=val%10
tail.next=ListNode(val)
l1=l1.next if l1 else None
l2=l2.next if l2 else None
tail=tail.next
return dummy.next
Comments
Post a Comment