1290. Convert Binary Number in a Linked List to Integer
Python
First try, O(2N)
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
length = 0
node = head
while node:
length += 1
node = node.next
result = 0
exp = length - 1
node = head
while node:
result += node.val * (2 ** exp)
exp = exp - 1
node = node.next
return result
Second try, optimize version, O(N + logN)
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
length = 0
node = head
while node:
length += 1
node = node.next
result = 0
exp = 2 ** (length - 1)
node = head
while node:
if node.val:
result += node.val * exp
exp = exp // 2
node = node.next
return result