Leetcode add-on list-python< two >

Source: Internet
Author: User

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 >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.