Add Two Numbers ii

Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Input: l1 = [0], l2 = [0]
Output: [0]
  • The number of nodes in each linked list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • It is guaranteed that the list represents a number that does not have leading zeros.
def add(l1,l2):
reverse(l1,l2)
traverse the linked list and add each corresponding node,
if any node is exhausted , then assume its value as 0
go on adding the corresponding element together with carry from,
previous addition
def add(l1,l2):
traverse the linked list
push l1 and l2 elements to the stack
pop the stack element and add them with carry
update new carry and also put the last digit of result to the new linked list

The solution

class Solution(object):
def addTwoNumbers(self, l1, l2):
ptr1,ptr2=l1,l2
one,two=[],[]
while(ptr1 or ptr2):
if ptr1:
one.append(ptr1.val)
ptr1=ptr1.next
if ptr2:
two.append(ptr2.val)
ptr2=ptr2.next
carry,temp=0,ListNode(0)
head=temp
while(one or two):
val1=one.pop() if one else 0
val2=two.pop() if two else 0
carry,rem=divmod(val1+val2+carry,10)
new_node=ListNode(rem)
new_node.next=temp.next
temp.next=new_node
if carry:
new_node=ListNode(carry)
new_node.next=temp.next
temp.next=new_node
return head.next

--

--

--

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Top Firebase Products In A Nutshell

Public Testnet Launch Simulation

You Probably Don’t Need Deep Links for Referrals

Making the Software Interview Work for You — Tip #1

About the prefetch count in RabbitMQ…

Key Takeaways From Our Cloud Infrastructure Lab

Where in the World is ‘Carbon.Sandy.Egos’?

HEAP SORT ALGORITHM

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhanarajappu

Dhanarajappu

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.

More from Medium

Data Structure Problem| Sort Colors in-Place | Part 2

Leetcode — Isomorphic Strings — Easy

Solution for Range Sum Query 2D immutable ( Easiest and Smartest Method 😎 )

Java Interview questions for 0 to 2 Years of experience