Created
June 1, 2020 22:28
-
-
Save rostand2017/6ed013341eda981aeb6bd46dd5a317f4 to your computer and use it in GitHub Desktop.
Add Two Number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ListNode: | |
def __init__(self, val=0, nextt=None): | |
self.val = val | |
self.nextt = nextt | |
def size(self): | |
i = 1 | |
nextt = self.nextt | |
while nextt != None: | |
nextt = nextt.nextt | |
i += 1 | |
return i | |
def addLast(self, val): | |
pred = self | |
nextt = self.nextt | |
while nextt != None: | |
pred = nextt | |
nextt = nextt.nextt | |
pred.nextt = ListNode(val=val) | |
def toArray(self): | |
tab = [] | |
tab.append(self.val) | |
nextt = self.nextt | |
while nextt != None: | |
tab.append(nextt.val) | |
nextt = nextt.nextt | |
return tab | |
class Solution: | |
def addTwoNumber(self, l1:ListNode, l2:ListNode): | |
return self.__sumSucc(l1, l2) if l1.size() > l2.size() else self.__sumSucc(l2, l1) | |
def __sumSucc(self, l1:ListNode, l2:ListNode): | |
resultList = ListNode() | |
firstNode = False | |
rest = 0 | |
_l1 = l1 | |
_l2 = l2 | |
while _l1: | |
sum_num = _l1.val + _l2.val + rest if _l2 != None else _l1.val + rest | |
rest = int(str(sum_num)[0]) if sum_num > 9 else 0 | |
used_digit = int(str(sum_num)[1]) if sum_num > 9 else sum_num | |
if not firstNode: | |
firstNode = True | |
resultList.val = used_digit | |
else: | |
resultList.addLast(used_digit) | |
_l1 = _l1.nextt | |
_l2 = _l2.nextt if _l2 != None else None | |
return resultList | |
listOne = ListNode(2, ListNode(4, ListNode(val=3))) | |
listTwo = ListNode(5, ListNode(6, ListNode(val=4))) | |
solution = Solution() | |
listResult = solution.addTwoNumber(listOne, listTwo) | |
listResult.toArray() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment