题目
Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number.
Return the decimal value of the number in the linked list.
解题思路
让结果等于头的数字,遍历链表,每次先将结果左移一位,然后与下一个链表中的数进行或运算
代码
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
num = head.val
while head.next:
num = (num << 1) | head.next.val
head = head.next
return num