[Leetcode] ADD Numbers @ Python

Source: Internet
Author: User

Original title address: https://oj.leetcode.com/problems/add-two-numbers/

Test instructions

You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.

Input: (2, 4, 3) + (5, 6, 4)
Output: 7, 0, 8

The idea of solving problems: the basic operation of the linked list. The methods is provided. Method 1 is much slimmer

#Definition for singly-linked list.#class ListNode:#def __init__ (self, x):#self.val = x#Self.next = NoneclassSolution:#@return a ListNode    defaddtwonumbers (self, L1, L2):#Method 1:14 LinesDummy, flag =ListNode (0), 0 head=Dummy whileFlagorL1orL2:node=listnode (flag)ifL1:node.val+=l1.val L1=L1.nextifL2:node.val+=L2.val L2=L2.next Flag= NODE.VAL/10Node.val%= 10Head.next=node Head= Head.next#Head.next, head = node, node        returnDummy.next"""# method 2:24 Lines if not l1:return L2 if not l2:return l1 dummy = listnode (0) p = Dummy flag = 0 while L1 and l2:tmp = l1.val + l2.val + flag P.next = ListNode (t                MP%) flag = TMP/10 L1, l2, p = l1.next, L2.next, p.next if l1:while L1:                TMP = L1.val + Flag P.next = ListNode (tmp%) flag = TMP/10 L1, p = l1.next, p.next if l2:while l2:tmp = l2.val + Flag P.next = Li Stnode (tmp%) flag = TMP/10 L2, p = l2.next, p.next if flag = = 1:p.next = Lis Tnode (flag) return Dummy.next"""

[Leetcode] ADD Numbers @ Python

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.