ez, just like how u would solve
class Solution:
def getDecimalValue(self, head: Optional[ListNode]) -> int:
bin_string=""
while head:
bin_string+=str(head.val)
head=head.next
ans=0
power=0
for i in range(len(bin_string)-1,-1,-1):
if bin_string[i]=="1":
ans+= 2**power
power+=1
return ans
but we can actually use a trick to iter from msb to lsb. If the value is 1, we can shift the accumulated value one bit to the left via ans = ans *2 .
For example if we had binary "10" and the current bit is 1, we need to shift 10 to the left and make it 100. Thats what ans*2 is doing. Then we just add a one if current bit is 1
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
answer = 0
while head:
answer = 2*answer + head.val
head = head.next
return answer
n time
n space my code