小黑夜晚冒雨加餐leetcode之旅:2. 两数相加

发布于:2023-01-12 ⋅ 阅读:(482) ⋅ 点赞:(0)

小黑做法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        # 由链表获取数字
        def get_num(l):
            temp = 0
            i = 1
            while l:
                num = l.val
                temp = num * i + temp
                i *= 10
                l = l.next
            return temp
        n1 = get_num(l1)
        n2 = get_num(l2)
        head = ListNode()
        link = head
        # 数字加和后输出链表
        for c in str(n1+n2)[::-1]:
            c = int(c)
            link.next = ListNode(val = c)
            link = link.next
        return head.next

在这里插入图片描述

模拟法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        head = ListNode()
        link = head
        # 进位
        carry = 0
        while l1 or l2:
            # 获取两个数字
            n1 = 0
            n2 = 0
            if l1:
                n1 = l1.val
                l1 = l1.next
            if l2:
                n2 = l2.val
                l2 = l2.next
            # 加和操作
            sum_ = n1 + n2 + carry
            # 添加结点
            link.next = ListNode(val = sum_ % 10)
            link = link.next
            # 计算进位
            carry = sum_ // 10
        # 判断进位
        if carry:
            link.next = ListNode(val=1)
    
        return head.next

在这里插入图片描述

小黑生活记录

晚上冒雨跟学长吃了串串香,感觉最近接连出去吃身体都扛不住了,需要调节一下了,不能老出去吃了。
在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到

热门文章