Home > Software design >  LeetCode python recursive solution
LeetCode python recursive solution

Time:09-17

So I saw this solution in leetcode discussions and I cannot wrap my head around it.

    # Definition for singly-linked list.
    class ListNode(object):
        def __init__(self, val=0, next=None):
            self.val = val
            self.next = next

    class Solution:
        def addTwoNumbers(self, l1, l2):
            def toint(node):
                a = node.val if node else 0 
                print(a) #prints 2 4 3
       HERE===> x = node.val   10 * toint(node.next) if node else 0
                print(x) #prints 3 4 2
                return x
            def tolist(n):
                node = ListNode(n % 10)
                if n > 9:
                    node.next = tolist(n / 10)

                return node
            return tolist(toint(l1)   toint(l2))

        
    a, a.next, a.next.next = ListNode(2), ListNode(4), ListNode(3)
    b, b.next, b.next.next = ListNode(5), ListNode(6), ListNode(4)
    result = Solution().addTwoNumbers(a, b)
    print("{0}, {1}, {2}".format(result.val, result.next.val, result.next.next.val))

What I don't understand is how does it take a number, add 10 and multiply by next and finally reverse them.

Can someone explain the line I marked HERE===>

CodePudding user response:

There's actually no addition by 10 or reversal. Some redundant parentheses show the order of operation. That line is exactly equivalent to

if node:
    x = node.val   (10 * toint(node.next))
else:
    x = 0

It appears that these linked lists have the least significant digit at the head, so no reversal is necessary to add them. That said, this is not an intended solution and takes advantage of Python's bignum, rather than adding values node by node.

  • Related