2. Add Two Numbers

 

https://leetcode.com/problems/add-two-numbers/


Algorithm

1
2
3
4
5
6
7
8
9
Input: l1, l2

sum ← 0
for l in [l1, l2]
  num_list ← all number sequence of l
  num ← convert num_list to number
  sum ← sum + num
rst ← convert sum to ListNode
return rst


Code

import numpy as np

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

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

      for l in (l1, l2):
        # Line 5
        num_list = np.array([], dtype=int)
        while True:
            num_list = np.append(num_list, l.val)
            if l.next is None:
              break
            l = l.next

        # Line 6
        num = np.sum(num_list * [10**i for i in range(len(num_list))])
        sum += num

      num_list = [int(i) for i in reversed(str(sum))]
      n = len(num_list)

      ListNodes = [ListNode(val) for val in num_list]
      for i in range(n):
        ListNodes[i].next = ListNodes[i + 1] if i < n - 1 else None
      return ListNodes[0]
272ms / 27.6MB