首页 > 其他 > 详细

【LeetCode】【Linked List】Convert binary number in a linked list to integer

时间:2020-07-01 09:48:54      阅读:60      评论:0      收藏:0      [点我收藏+]

题目:

给定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.
【待续,目前我与链表不熟。。。

 

【LeetCode】【Linked List】Convert binary number in a linked list to integer

原文:https://www.cnblogs.com/jialinliu/p/13217383.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!