HTMLify

LeetCode - Add Two Numbers - Python
Views: 10 | Author: abh
# Definition for singly-linked list.
# 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]:
        n1 = 0
        d = 1
        while l1.next != None:
            n1 +=  (l1.val * d)
            l1 = l1.next
            d *= 10
        n1 +=  (l1.val * d)

        n2 = 0
        d = 1
        while l2.next != None:
            n2 +=  (l2.val * d)
            l2 = l2.next
            d *= 10
        n2 +=  (l2.val * d)

        ans = ListNode()
        c = ans
        s = str(n1+n2)[::-1]
        for i in range(len(s)):
            n = int(s[i])
            c.val = n
            if i != len(s) -1:
                c.next = ListNode()
                c = c.next
        
        return ans

Comments

abh 2025-01-10 18:17

Finally I am able to solve LeetCode's problem no 2