描述
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.
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
Note:
The Linked List is not empty.
Number of nodes will not exceed 30.
Each node's value is either 0 or 1.
解析
根据题意,其实就是求链表组成的字符串表示的二进制数转化为十进制的值,就是一个简单的二进制转十进制问题,直接按照链表的顺序从前到后进行计算即可,当前节点所对应的十进制数为之前的 res * 2 + 当前的节点的值,遍历结束得到的 res 即可结果。
解答
class Solution(object):
def getDecimalValue(self, head):
"""
:type head: ListNode
:rtype: int
"""
res = head.val
while head.next:
res = res * 2 + head.next.val
head = head.next
return res
运行结果
Runtime: 16 ms, faster than 81.12% of Python online submissions for Convert Binary Number in a Linked List to Integer.
Memory Usage: 13.5 MB, less than 15.05% of Python online submissions for Convert Binary Number in a Linked List to Integer.
原题链接:https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer/
您的支持是我最大的动力