美文网首页
leetcode 2. 两数相加

leetcode 2. 两数相加

作者: 七齐起器 | 来源:发表于2021-04-25 13:59 被阅读0次
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            ptr1=l1
            ptr2=l2
            tmp=0
            rtn_node=None
            while ptr1!= None or ptr2!= None:
                tmp_node=ListNode()
                if ptr1==None:
                    tmp_node.val=ptr2.val+tmp-(ptr2.val+tmp)/10*10 if ptr2.val+tmp>=10 else ptr2.val+tmp
                    tmp=(ptr2.val+tmp)/10
                if ptr2==None:
                    tmp_node.val=ptr1.val+tmp-(ptr1.val+tmp)/10*10 if ptr1.val+tmp>=10 else ptr1.val+tmp
                    tmp=(ptr1.val+tmp)/10
                if ptr1!=None and ptr2!=None:
                    tmp_node.val=ptr1.val+ptr2.val+tmp-(ptr1.val+ptr2.val+tmp)/10*10 if ptr1.val+ptr2.val+tmp>=10 else ptr1.val+ptr2.val+tmp
                    tmp=(ptr1.val+ptr2.val+tmp)/10
                if rtn_node==None:
                    rtn_node=tmp_node
                    ptr3=rtn_node
                else:
                    ptr3.next=tmp_node
                    ptr3=tmp_node
                try:
                    ptr1=ptr1.next
                except:
                    pass
                try:
                    ptr2=ptr2.next
                except:
                    pass 
            if tmp>0:
                tmp_node=ListNode()
                tmp_node.val=tmp
                ptr3.next=tmp_node
                ptr3=tmp_node
            return rtn_node
    
    
    

    相关文章

      网友评论

          本文标题:leetcode 2. 两数相加

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