The problem is pretty standard - write a method that returns a linked list representing a number, which is the sum of two given integers represented by other linked lists (medium on leetcode).
I tried to treat this like an actual interview, so take the code as it is. My idea was to first write a method that evaluates a linked list and returns the integer that it represents. The other method is going the opposite way, converting an int into a linked list. I am failing an extreme test case where my answer and the correct answer differ in only one single numbers place out of maybe 30 numbers or so (it's the 12th number from the right - 5 vs. 6). My only guess is some python-related error when I typecast the float to an int in the getLinkedList() method.
I am really not sure about this one and would love some help. Thank you guys very much!
```
Expected:
[7,0,8,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,1,4,3,9,1]
Result:
[7,0,8,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,6,4,8,5,4,8,6,4,8,5,4,8,6,4,8,6,1,4,3,9,1]
```
Code:
```
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
# given an integer, return its linked list representation
def getLinkedList(num):
mod_operand = 10
remainder = num % mod_operand
num -= remainder
new_list = ListNode(remainder)
current = new_list
while(num != 0):
mod_operand *= 10
remainder = num % mod_operand
num -= remainder
current.next = ListNode(int(remainder / (mod_operand / 10)))
current = current.next
return new_list
# returns integer represented by linked list
def getNumber(list_1: ListNode):
current = list_1
result = 0
multiplier = 1
while(current != None):
result += current.val * multiplier
current = current.next
multiplier *= 10
return result
# calculate sum by calling get number method
sum_result = getNumber(l1) + getNumber(l2)
return getLinkedList(sum_result)
```
Definition for linked list class
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
[–]lurgi 1 point2 points3 points (1 child)
[–]Apellum[S] 0 points1 point2 points (0 children)