Demo entry 6788994

Python

   

Submitted by anonymous on Apr 24, 2019 at 14:16
Language: Python 3. Code size: 1.6 kB.

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:        
        res = ListNode(0)
        c = res
        carry = 0
        while(l1 and l2):
            c.next = ListNode(0)
            c = c.next
            c.val = (l1.val + l2.val + carry) % 10
            carry = (l1.val + l2.val + carry) // 10
            l1 = l1.next
            l2 = l2.next
        if l1 == None:
            t = l2
        else:
            t = l1
        if carry > 0:
            while t:
                c.next = ListNode(0)
                c = c.next
                c.val = (t.val + carry) % 10
                carry = (t.val + carry) // 10
                t = t.next
            if carry > 0:
                c.next = ListNode(0)
                c = c.next
                c.val = carry
        else:
            c.next = t
        return res.next

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        sum = ListNode(0)
        head = sum
        carry = 0

        while True:
            if l1 != None:
                sum.val += l1.val
                l1 = l1.next

            if l2 != None:
                sum.val += l2.val
                l2 = l2.next

            sum.val += carry
            carry = int(sum.val / 10)
            sum.val %= 10

            if l1 != None or l2 != None or carry > 0:
                sum.next = ListNode(0)
                sum = sum.next
            else:
                break
        
        return head            

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).