LeetCode 2. 两数相加
Posted tonydandelion2014
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 2. 两数相加相关的知识,希望对你有一定的参考价值。
2. 两数相加 add-two-numbers(中)
考察知识点
链表的声明
核心思想
设立一个表示进位的变量carried
,建立一个新链表,把输入的两个链表从头往后同时处理,每两个相加,将结果加上carried
后的值作为一个新节点到新链表后面。
图示
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-P36Njp6Y-1583596344052)(http://q3q41dfs4.bkt.clouddn.com/lchmg.gif)]
注意事项
-
C++链表中的操作都是基于指针进行的。指针指向的是ListNode。
-
当链表以struct声明时,用
->
获取其元素。ListNode* p = l1; cout << p->val << endl;
代码
方法一
class ListNode():
def __init__(self, val):
if isinstance(val,int):
self.val = val
self.next = None
elif isinstance(val,list):
self.val = val[0]
self.next = None
cur = self
for i in val[1:]:
cur.next = ListNode(i)
cur = cur.next
def gatherAttrs(self):
return ", ".join(": ".format(k, getattr(self, k)) for k in self.__dict__.keys())
def __str__(self):
return self.__class__.__name__+" "+"".format(self.gatherAttrs())+""
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
if isinstance(l1,list):
l1 = ListNode(l1)
l2 = ListNode(l2)
re = ListNode(0)
r=re
carry=0
while(l1 or l2):
x= l1.val if l1 else 0
y= l2.val if l2 else 0
s=carry+x+y
carry=s//10
r.next=ListNode(s%10)
r=r.next
if(l1!=None):l1=l1.next
if(l2!=None):l2=l2.next
if(carry>0):
r.next=ListNode(1)
return re.next
if __name__ == "__main__":
test = Solution()
print(test.addTwoNumbers([1,3],[2,1,3]))
- 方法二
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# maybe standard version
def _addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p = dummy = ListNode(-1)
carry = 0
while l1 and l2:
p.next = ListNode(l1.val + l2.val + carry)
carry = p.next.val / 10
p.next.val %= 10
p = p.next
l1 = l1.next
l2 = l2.next
res = l1 or l2
while res:
p.next = ListNode(res.val + carry)
carry = p.next.val / 10
p.next.val %= 10
p = p.next
res = res.next
if carry:
p.next = ListNode(1)
return dummy.next
# shorter version
def addTwoNumbers(self, l1, l2):
p = dummy = ListNode(-1)
carry = 0
while l1 or l2 or carry:
val = (l1 and l1.val or 0) + (l2 and l2.val or 0) + carry
carry = val / 10
p.next = ListNode(val % 10)
l1 = l1 and l1.next
l2 = l2 and l2.next
p = p.next
return dummy.next
if __name__ == "__main__":
print("hello world!")
solution = Solution()
l1 = ListNode([2,4,3])
l2 =
ListNode([5,6,4])
solution.addTwoNumbers(l1, l2)
总结
这个题目做的太久了,主要犯了以下几个错误!
1、把for (int i = 0; i<len1-len2; i++)或for (int i = 1; i<=len1-len2; i++)
错写成for (int i = 1; i<len1-len2; i++)
一字之差搞了半天。
以上是关于LeetCode 2. 两数相加的主要内容,如果未能解决你的问题,请参考以下文章