Add Two Numbers

Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [7,0,8]
Explanation: 342 + 465 = 807.
Input: l1 = [0], l2 = [0]
Output: [0]
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
Output: [8,9,9,9,0,0,0,1]
  • 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.
class Solution(object):
def addTwoNumbers(self, l1, l2,carry=0):
#print(l1.val,l2.val,bool(l1),bool(l2))
val1,val2=0,0

val1=l1.val if l1 else 0
val2=l2.val if l2 else 0
carry,quotient=divmod(val1+val2+carry,10)
node=ListNode(quotient)
l1= l1.next if l1 else l1
l2= l2.next if l2 else l2
if l1 or l2 or carry:
node.next=self.addTwoNumbers(l1,l2,carry)
return node
class Solution(object):
def addTwoNumbers(self, l1, l2):
carry=0
temp=ListNode(0)
node_=temp
while l1 or l2:
if l1 ==None:
one=0
else:
one=l1.val

if l2==None:
two=0
else:
two=l2.val
inter=ListNode((one+two+carry)%10)
temp.next=inter
temp=inter
carry=(one+two+carry)//10
if l1:
l1=l1.next
if l2:
l2=l2.next
if carry!=0:
temp.next=ListNode(carry)

return node_.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

Serverless Functions using Next.js API routes

Top 5 JavaScript Libraries — May 2017

New useful JavaScript features added in Chrome 80

Developer Spotlight: Kyle Mathews of Gatsby

How to delete node_modules in the simplest way

How to remove node_modules

RAID is not equal to per block checksumming

React Memo Briefly

React JS: Conditional Rendering and how to implement Geolocation

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

DSA Pandemic #1: Recursion

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

Big O Notation - 1

Linked Lists — Data Structures