02.leetcode题目讲解(Python):两数相加

题目:

给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

答案的思路是通过初等数学中的借位来进行计算,我的思路是先获取 l1, l2 的确切数值,通过位数(个十百千万)来进行计算。我的算法复杂度为 O(m + n)其中 m 和 n 为 l1, l2 的位数。比起答案思路,我的算法复杂度要高一些。

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


class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # n is the node of l1
        n = l1
        i = 1
        num_l1 = 0
        # get num of l1
        while n:
            num_l1 = num_l1 + n.val * i
            i = i * 10
            n = n.next

        # m is the node of l2
        m = l2
        j = 1
        num_l2 = 0
        # get num of l2
        while m:
            num_l2 = num_l2 + m.val * j
            j = j * 10
            m = m.next
        # get the sum of l1 , l2
        str_num = str(num_l1 + num_l2)
        # reverse str_num
        str_num = str_num[::-1]
        # turn to list output
        list_result = []
        for s in str_num:
            list_result.append(int(s))
        return list_result

返回为链表的版本:

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        n = l1
        i = 1
        num_l1 = 0
        # get num of l1
        while n:
            num_l1 = num_l1 + n.val * i
            i = i * 10
            n = n.next

        m = l2
        j = 1
        num_l2 = 0
        # get num of l2
        while m:
            num_l2 = num_l2 + m.val * j
            j = j * 10
            m = m.next

        str_num = str(num_l1 + num_l2) 
        str_num = str_num[::-1]
        res = list_result = ListNode(0)
        
        for s in str_num:
            list_result.next = ListNode(int(s))
            list_result = list_result.next          
        return res.next

ps:如果您有好的建议,欢迎交流 :-D,也欢迎访问我的个人博客 苔原带:tundrazone.com

你可能感兴趣的:(02.leetcode题目讲解(Python):两数相加)