Two python solutions(one recursion and another o(1) space)


  • 6
    W
    # 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, tmp=0):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            #较少的代码(递归)但是较低的效率和较多的空间
            # if not(tmp or l1 or l2):
            #     return None
            # l1 = l1 or ListNode(0)
            # l2 = l2 or ListNode(0)
            # r_node = ListNode((l1.val + l2.val + tmp)%10)
            # tmp = (l1.val + l2.val + tmp)/10
            # r_node.next = self.addTwoNumbers(l1.next,l2.next,tmp)
            # return r_node
            
            #较多的代码但是较高的效率和较少的空间(原地)
            tmp, l1.val = divmod(l1.val + l2.val, 10)
            r = l1
            
            while (l1.next and l2.next):
                tmp, l1.next.val = divmod(l1.next.val + l2.next.val + tmp, 10)
                l1 = l1.next
                l2 = l2.next
            if l2.next:
                l1.next = l2.next
            while l1.next and tmp:
                tmp, l1.next.val = divmod(l1.next.val + tmp, 10)
                l1 = l1.next
            if tmp:
                l1.next = ListNode(1)
            return r

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.