leetcode

力扣–两数相加 python

在这里插入图片描述
注:
sum % 10是当前位的数
sum // 10是进位的数
利用carry来标记进位

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        
        def add(l, r, carry):
            
            if not l and not r and not carry:
                return None
            sum = (l.val if l else 0) + (r.val if r else 0) + carry
            node  = ListNode(sum % 10)
            node.next = add((l.next if l else None), (r.next if r else None), sum // 10)
            return node
        return add(l1, l2, 0)     

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页