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

JavaScript Blog

React.JS: An Introduction to Cross-platform tutorial

UPLOAD IMAGE IN CLOUDINARY USING MERN STACK

Spiral Matrix Traversal in JavaScript

LeetCode — Container with Most Water

Next Level Reducers

Setting up Firebase Authentication in React Application

Build an Imgur Client with React Native and MobX — React Native School

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

Quick Sort (With 3 partitions)

The Linked List Data Structure

Basic Concepts of Object-Oriented Programming — Infovistar

Partitions → Interviewbit Arrays Problem