美文网首页Leetcode
2. Add Two Numbers

2. Add Two Numbers

作者: oo上海 | 来源:发表于2016-08-07 23:51 被阅读9次

    2. Add Two Numbers

    题目:
    https://leetcode.com/problems/add-two-numbers/

    难度 : Medium

    跟plus One, add Binary 玩的同一种花样

    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            #easiest case
            if l1 == None:
                return l2
            if l2 == None:
                return l1
            
            if l1.val + l2.val < 10:
                l3 = ListNode(l1.val + l2.val)
                l3.next = self.addTwoNumbers(l1.next, l2.next)
    
            elif l1.val + l2.val >= 10:
                l3 = ListNode(l1.val + l2.val - 10)
                tmp = ListNode(1)
                tmp.next = None
                l3.next = self.addTwoNumbers(l1.next, self.addTwoNumbers(l2.next ,tmp))
            return l3
    

    相关文章

      网友评论

        本文标题:2. Add Two Numbers

        本文链接:https://www.haomeiwen.com/subject/dbnlsttx.html