Leetcode "Add Numbers" Python implementation

Source: Internet
Author: User
Tags add numbers

title :

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

code : OJ Test via runtime:171 ms

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@return a ListNode9     defaddtwonumbers (self, L1, L2):Ten         ifL1 isNone: One             returnL2 A         ifL2 isNone: -             returnL1 -          theDummyhead =listnode (0) -p =listnode (0) -Dummyhead.next =P -          +Jinwei =0 -          whileL1 is  notNone andL2 is  notNone: +Curr_total = l1.val + L2.val +Jinwei AL1 =L1.next atL2 =L2.next -Curr_digit = curr_total% 10 -Jinwei = CURR_TOTAL/10 -Curr_node =ListNode (curr_digit) -P.next =Curr_node -p =P.next in              -         ifL1 is  notNone: to              whileL1 is  notNone: +Curr_total = L1.val +Jinwei -L1 =L1.next theCurr_digit = curr_total% 10 *Jinwei = CURR_TOTAL/10 $Curr_node =ListNode (curr_digit)Panax NotoginsengP.next =Curr_node -p =P.next the         ifL2 is  notNone: +              whileL2 is  notNone: ACurr_total = L2.val +Jinwei theL2 =L2.next +Curr_digit = curr_total% 10 -Jinwei = CURR_TOTAL/10 $Curr_node =ListNode (curr_digit) $P.next =Curr_node -p =P.next -          the         ifJinwei = = 1: -Curr_node = ListNode (1)WuyiP.next =Curr_node the          -         returnDummyhead.next.next

Ideas :

It's the addition operation. Note that all values on the two-linked list have a carry after calculation, and if there is a carry, it needs to be processed.

Leetcode "Add Numbers" Python implementation

Related Article

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.