mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Create add_two_numbers.py
This commit is contained in:
parent
e5c9084b64
commit
b068e60212
37
linked_lists/add_two_numbers.py
Normal file
37
linked_lists/add_two_numbers.py
Normal file
@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# author: bt3gl
|
||||
|
||||
|
||||
class Node:
|
||||
|
||||
def __init__(self, val):
|
||||
self.val = val
|
||||
self.next = None
|
||||
|
||||
def add_two_numbers(l1, l2):
|
||||
|
||||
n1, n2, i = '', '', 1
|
||||
|
||||
while l1:
|
||||
n1 += str(l1.val)
|
||||
l1 = l1.next
|
||||
|
||||
while l2:
|
||||
n2 += str(l2.val)
|
||||
l2 = l2.next
|
||||
|
||||
n1 = int(n1[::-1])
|
||||
n2 = int(n2[::-1])
|
||||
n = str(n1 + n2)[::-1]
|
||||
|
||||
current = ListNode(n[0])
|
||||
head = current
|
||||
|
||||
while i < len(n):
|
||||
current.next = ListNode(n[i])
|
||||
current = current.next
|
||||
i += 1
|
||||
|
||||
return head
|
||||
|
Loading…
x
Reference in New Issue
Block a user