leetcode no.2 add two numbers

  • 第一种写法:先将listnode组成的链表转化为字符串,再由字符串转化为int再相加,再转化为子串,再转化为列表输出。容易些
  • 第二种写法:遍历链表

第一种:92ms


class (object):
def __init__(self, x):
self.val = x
self.next = None
def create(self, lst):
cur = self
for i,v in enumerate(lst):
cur.val = v
if i != len(lst) - 1:
tmp = ListNode(0)
cur.next = tmp
cur = tmp

def printf(self):
head = self
while head:
print(head.val)
head = head.next



class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
list1 = []
list2 = []
while l1:
list1.insert(0,str(l1.val))
l1 = l1.next
while l2:
list2.insert(0,str(l2.val))
l2 = l2.next
sum1 = int(''.join(list1))
sum2 = int(''.join(list2))
sum = sum1 + sum2
list3 = list(reversed(list(str(sum))))
list3 = [int(x) for x in list3]
return list3

if __name__ == "__main__":
l1 = ListNode(0)
l1.create([1,4,5])
l1.printf()
l2 = ListNode(0)
l2.create([3,6,3])
l2.printf()
sol= Solution()
ans = sol.addTwoNumbers(l1,l2)
print(ans)

第二种写法:100ms

def addTwoNumbers(self, l1, l2):
carry = 0
cur = l3 = ListNode(0)
while l1 or l2:
sum = carry
if l1:
sum = sum + l1.val
l1 = l1.next
if l2:
sum = sum + l2.val
l2 = l2.next
if sum >= 10:
sum = sum - 10
carry = 1
else:
carry = 0

cur.val = sum
if l1 or l2:
tmp = ListNode(0)
cur.next = tmp
cur = tmp
if carry == 1:
tmp = ListNode(1)
cur.next = tmp
return l3