LeetCodeLinked ListConvert binary number in a linked list to integer

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCodeLinked ListConvert binary number in a linked list to integer相关的知识,希望对你有一定的参考价值。

题目:

给定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:

  • The Linked List is not empty.
  • Number of nodes will not exceed 30.
  • Each node\'s value is either 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
Runtime: 32 ms, faster than 53.18% of Python3 online submissions for Convert Binary Number in a Linked List to Integer.
Memory Usage: 14 MB, less than 7.31% of Python3 online submissions for Convert Binary Number in a Linked List to Integer.
 
【解法】
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        answer = 0
        while head: 
            answer = 2*answer + head.val 
            head = head.next 
        return answer
Runtime: 24 ms, faster than 94.07% of Python3 online submissions for Convert Binary Number in a Linked List to Integer.
Memory Usage: 13.9 MB, less than 28.38% of Python3 online submissions for Convert Binary Number in a Linked List to Integer.
【待续,目前我与链表不熟。。。

 

以上是关于LeetCodeLinked ListConvert binary number in a linked list to integer的主要内容,如果未能解决你的问题,请参考以下文章