Leetcode 2. ADD Numbers Problem Solving report

Source: Internet
Author: User

Test instructions: There are two linked lists, which represent two non-negative numbers in reverse order. Example (2, 4, 3) represents 342, which is two digits and is output in reverse order in the same way. As 342+465 = 807, you need to show the result as (7->0->8). Idea: Simulation of the addition of the operation process, from the start of the bit, carry save down, 10 bits of the operation when the digit of the plus, and so on. C + + Code
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* AddTwoNumbers (listnode* L1, listnode*L2) {ListNode Prehead (0), *p = &Prehead; intExtra =0;  while(L1 | | l2 | |extra) {            intsum = (L1? L1->val:0) + (L2? L2->val:0) +Extra; Extra= SUM/Ten; P->next =NewListNode (sum%Ten); P= p->Next; L1= L1? L1->next:l1; L2= L2? L2->Next:l2; }        returnPrehead.next; }};
Python Code
#Definition for singly-linked list.#class ListNode (object):#def __init__ (self, x):#self.val = x#Self.next = Noneclasssolution (object):defaddtwonumbers (self, L1, L2):""": Type L1:ListNode:type l2:ListNode:rtype:ListNode"""P= Prehead =listnode (0) Extra=0 whileL1orL2orExtra:extra, Val= Divmod ((L1 andL1.valor0) + (L2 andL2.valor0) + Extra, 10) P.next=ListNode (val) P=P.nextifL1:L1=L1.nextifL2:l2=L2.nextreturnPrehead.next
JS Code
/** Definition for singly-linked list. * Function ListNode (val) {* This.val = val; * This.next = null; *} 
    *//** * @param {listnode} L1 * @param {listnode} L2 * @return {ListNode}*/varAddTwoNumbers =function(L1, L2) {varPrehead =NewListNode (0)    varp =PreheadvarExtra = 0 while(L1!==NULL|| L2!==NULL|| Extra!== 0) {        varsum = (L1 && l1.val | | 0) + (L2 && L2.val | | 0) +Extra Extra= (Sum > 9)? 1:0P.next=NewListNode (sum% 10) P=p.next L1= L1 && L1.next | |NULLL2= L2 && L2.next | |NULL    }    returnPrehead.next};

Leetcode 2. ADD Numbers Problem Solving report

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.