I have a linked list which represents the large number 2253239487.
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __repr__(self):
return '{0}'.format(self.val)
The ListNode instance is populated as below:
h1 = ListNode(2)
n2 = ListNode(2)
n3 = ListNode(5)
n4 = ListNode(3)
n5 = ListNode(2)
n6 = ListNode(3)
n7 = ListNode(9)
n8 = ListNode(4)
n9 = ListNode(8)
n10 = ListNode(7)
h1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
n7.next = n8
n8.next = n9
n9.next = n10
Now, I want to divide the number by 3 and return the answer as a whole number.
I have written below code but it is giving wrong result:
sum = 0
head = h1
while head.next:
sum += head.val
head = head.next
return sum // 3
There is an assumption that the "sum" integer is too big for the integer object. What is the best way to directly calculate avg without storing sum in memory?