码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode(2)两数相加

时间:2019-10-10 00:25:25      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:obj   ret   pre   整数   __init__   self   tco   ber   一个   

Leetcode(2)两数相加

[题目表述]:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

第一种方法:大众解法

执行用时:80 ms; 内存消耗:12.2MB

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        cLow=0
        l4=ListNode(0)
        l3=l4
        while l1 or l2 :
            x= l1.val if l1 else 0        //学习
            y= l2.val if l2 else 0
            if x+y+cLow<10 :
                l3.next=ListNode(x+y+cLow)
                cLow=0
                l3=l3.next
                if(l1!=None):l1=l1.next
                if(l2!=None):l2=l2.next
            else:
                l3.next=ListNode(x+y+cLow-10)
                cLow=1
                l3=l3.next
                if(l1!=None):l1=l1.next
                if(l2!=None):l2=l2.next
        if cLow>0 : l3.next=ListNode(cLow)
        return l4.next

注意

  • 一结点为空,另一结点不为空

  • 最高位相加>10进位

学习

  • l1 or l2

  • ListNode用法

  • x= l1.val if l1 else 0 ***

Leetcode(2)两数相加

标签:obj   ret   pre   整数   __init__   self   tco   ber   一个   

原文地址:https://www.cnblogs.com/ymjun/p/11645061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!