标签:not strong upload ima lis ssi loading ber png
题目:
给定head(头节点),它是单链表的参考节点。 链表中每个节点的值为0或1。链表中包含数字的二进制表示形式。返回链接列表中数字的十进制值。
Example 1:
Input: head = [1,0,1] Output: 5 Explanation: (101) in base 2 = (5) in base 10
Example 2:
Input: head = [0] Output: 0
Example 3:
Input: head = [1] Output: 1
Example 4:
Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0] Output: 18880
Example 5:
Input: head = [0,0] Output: 0
Constraints:
30
.0
or 1
.【解法】
图源自@YaoFrankie
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def getDecimalValue(self, head: ListNode) -> int: ans = 0 while head: ans = (ans << 1) | head.val head = head.next return ans
class Solution: def getDecimalValue(self, head: ListNode) -> int: answer = 0 while head: answer = 2*answer + head.val head = head.next return answer
【LeetCode】【Linked List】Convert binary number in a linked list to integer
标签:not strong upload ima lis ssi loading ber png
原文地址:https://www.cnblogs.com/jialinliu/p/13217383.html