Previous: Leetcode Two and-python< >
Title: https://leetcode-cn.com/problems/add-two-numbers/description/
A two non-empty list is given to represent two non-negative integers. The digits are stored in reverse order, with each node storing only a single number. Adds two numbers to return a new linked list.
You can assume that except for the number 0, none of the two numbers will start with 0.
Example:
Input: (2, 4, 3) + (5, 6, 4) output: 7, 0, 8 reason: 342 + 465 = 807
Key points: Carry (10 plus one here), pointer movement (move to the next node here)
ClassSolution:DefAddTwoNumbers (self, L1, L2):""": Type L1:ListNode:type L2:ListNode:rtype:ListNode"""Ans = listnode (0)#Create a new node with an initial value of 0 temp =Ans TempSum =0WhileTrue:if (L1! =None): TempSum = L1.val + tempsum#L1 linked list node value added to the sum L1 = L1.next#The pointer points to the next nodeif (L2! =None): TempSum = TempSum + l2.val#L2 linked list node value added to the sum L2 = L2.next#The pointer points to the next nodeTemp.val = tempsum% 10#Take remainder (full 10 carry), assign value of current nodeprint(tempsum) tempsum = Int (TEMPSUM/10) # Gets the carry number assigned to the sum (for example, the TempSum is 10 into 1 bits, otherwise the carry is 0), the next node is added, and the new sum begins. if L1 = = None and L2 = = None and TempSum = = 0: # until there is no carry, and the node bit empty, jump out of the loop. (This adds tempsum==0 condition because the last two sections break # points and values may be greater than ten) Temp.next = ListNode (0) # New next node, storage and temp = Temp.next # pointer points to the next node return ans
Time complexity: O (max (L1 length, l2 length), Space complexity: O (max (L1 length, L2 length))
Leetcode add-on list-python< two >