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