程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved