Add Two Numbers (LeetCode Problems)
Today you will learn about one more problem of leetcode i.e. add two number.
In this problem you have given two linked list with reversed order numbers, you have to add two numbers from the linked list and return them as sum.
For example: [3,4,2][4,6,5] => [8,0,7] so in question you have asked for reverse order so it will be [7,0,8] as sum of number.
Let's solve this problem:-
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
result = ListNode(0)
result_tail = result
carry = 0
while l1 or l2 or carry:
val1 = (l1.val if l1 else 0)
val2 = (l2.val if l2 else 0)
carry, out = divmod(val1+val2 + carry, 10)
result_tail.next = ListNode(out)
result_tail = result_tail.
l1 = (l1.next if l1 else None)
l2 = (l2.next if l2 else None)
return result.next
First thing is that we have created a class which is collecting all the nodes(Values).
After that in second class, we are adding the numbers and returning to the class.
This is medium level question but quite easy it was!
We will meet with another questions till then enjoy Coding!