LeetCode 2. Add Two Numbers

题目

这里写图片描述

思路

用一个数表示进位。

代码

# 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
        """
        addNum = 0
        head = ListNode(0)
        p = head
        while l1 or l2:
            if l1 and l2:
                sumNum = l1.val + l2.val + addNum
            elif l1:
                sumNum = l1.val + addNum
            elif l2:
                sumNum = l2.val + addNum
            tmpNode = ListNode(sumNum)
            if sumNum >= 10:
                sumNum -= 10
                addNum = 1
                tmpNode.val = sumNum
            else:
                addNum = 0
            p.next = tmpNode
            p = p.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        if addNum:
            tmpNode = ListNode(1)
            p.next = tmpNode
        return head.next

阅读更多

扫码向博主提问

sparksnail

非学,无以致疑;非问,无以广识
去开通我的Chat快问
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y12345678904/article/details/79945970
个人分类: OJ-LeetCode 算法-树
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭