Leetcode 2 Add Numbers

Source: Internet
Author: User
Tags add numbers

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

Method One:

Standard list operation, note rounding and when a list is gone.

Note that the last one if there is a carry no settlement needs to be manually added 1 bits.

defadd_two_numbers (L1, L2)returnL1ifL2.nil? returnL2ifL1.nil? Ans=listnode.new (0) Cur=ans temp=0 whileL1 andL2 Cur.next= Listnode.new ((l1.val + l2.val + temp)% 10) Temp= (L1.val + l2.val + temp)/10L1=L1.next L2=L2.next cur=Cur.next End whileL1 Cur.next= Listnode.new ((l1.val + temp)%10) Temp= (L1.val + temp)/10L1=L1.next cur=Cur.next End whileL2 Cur.next= Listnode.new ((l2.val + temp)%10) Temp= (L2.val + temp)/10L2=L2.next cur=Cur.next End Cur.next= Listnode.new (temp%10)ifTemp >0 Ans.nextend

Method Two:

Python, Ruby does not overflow, can be converted into numbers added and then back to the linked list.

defadd_two_numbers (L1, L2)returnL1ifL2.nil? returnL2ifL1.nil? S1=array.new S2=array.new N=array.new whileL1 s1.unshift (l1.val) L1=L1.next End whileL2 S2.unshift (l2.val) L2=L2.next End x= s1.join.to_i+s2.join.to_i N= X.to_s.chars.map (&: to_i) ans=listnode.new (0) d=ans n.length.times do d.next=listnode.new (n.pop) d=D.next End Ans.nextend

Leetcode 2 Add Numbers

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.