Leetcode(2)两数相加

时间:2024-07-30 08:33:44

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 ***