Python两数相加

2021-02-08 06:18

阅读:431

标签:node   lis   append   efi   除了   end   self   lang   sel   

两数相加

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

思路一:

# 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:
        lst1 = []
        while l1:
            lst1.append(l1.val)
            l1 = l1.next
        lst2 = []
        while l2:
            lst2.append(l2.val)
            l2 = l2.next
        m, n = len(lst1), len(lst2)
        if m  9:
                num = num - 10
                lst3.append(num)
                if i == m - 1:
                    lst3.append(1)
                else:
                    lst1[i + 1] += 1
            else:
                lst3.append(num)
        node = ListNode(lst3[0])
        cur = node
        for i in lst3[1:]:
            node_ = ListNode(i)
            cur.next = node_
            cur = node_
        return node

思路二:

# 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:
        jin_wei = 0
        head = cur = None
        while l1 or l2:
            l1_val = l1.val if l1 else 0
            l2_val = l2.val if l2 else 0
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else  None
            num = l1_val + l2_val
            if jin_wei == 1:
                num += 1
                jin_wei = 0
            if num > 9:
                num = num - 10
                jin_wei = 1
            if not head:
                head = ListNode(num)
                cur = head
            else:
                node = ListNode(num)
                cur.next = node
                cur = node
        if jin_wei == 1:
            cur.next = ListNode(1)
        return head

Python两数相加

标签:node   lis   append   efi   除了   end   self   lang   sel   

原文地址:https://www.cnblogs.com/zyyhxbs/p/12771778.html


评论


亲,登录后才可以留言!