Leetcode daily question (implemented in Python) 02- adding two numbers
編輯:Python
class Solution:
def addTwoNumbers(self, l1, l2):
""" :type l1: ListNode :type l2: ListNode :rtype: ListNode """
# # Define a new join table pseudo pointer , Pointer to the head , Return results
# re = ListNode(0)
# # Define a movable pointer , Used to point to the location where the sum of two numbers is stored
# r = re
# # Define a carry pointer , Used to store when the sum of two numbers is greater than 10 When ,
# carry = 0
# while(l1 or l2):
# # If l1 It's not equal to null when , Take his value , be equal to null when , Just assign 0, Keep two linked lists with the same number of digits
# x = l1.val if l1 else 0
# # If l2 It's not equal to null when , Take his value , be equal to null when , Just assign 0, Keep two linked lists with the same number of digits
# y = l2.val if l2 else 0
# # The values of the two linked lists , Add additivity , And add the carry
# s = carry+x+y
# # Calculate the progression
# carry = s//10
# # Assign the summation number to the node of the new linked list ,
# # Note that at this time, you can't directly sum Assign a value to cur.next = sum. At this time, the type mismatch will be reported .
# # So we need to create a new node at this time , Assign values to nodes
# r.next=ListNode(s % 10)
# # Move the node of the new linked list back
# r = r.next
# # When linked list l1 It's not equal to null When , take l1 Move the node back
# if(l1!=None):
# l1=l1.next
# # When linked list l2 It's not equal to null When , take l1 Move the node back
# if(l2!=None):
# l2=l2.next
# # If the last two numbers , When there are carry digits when adding , Just carry the number , Give a new node to the linked list .
# # The sum of two numbers is less than at most 20, So the maximum value of can only be 1
# if(carry>0):
# r.next = ListNode(1)
# # Return the head node of the linked list
# return re.next
re = ListNode(0)
re_copy = re
carry = 0
while (l1 or l2):
x = l1.val if l1 else 0
y = l2.val if l2 else 0
sum = carry + x + y
carry = sum // 10
re_copy.next = ListNode(sum % 10)
re_copy = re_copy.next
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if (carry > 0):
re_copy.next = ListNode(1)
return re.next