提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
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
这是一题关于单链表的题目,每个单链表都有一个头指针 Head
作为开端,然后指向下一个节点 Node
,而每一个节点都由一个 Next
指针指向下一个节点。
这题的思路比较简单,遍历整个链表把每一个二进制的0和1存到一个字符串里,再通过Python的int()将二进制的数转化成十进制。
Python - 第一个方法:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def getDecimalValue(self, head):
"""
:type head: ListNode
:rtype: int
1. enumerate the linked list and add val to a string
2. transfer string to integer
"""
S = ""
while head:
S += str(head.val) # remember to convert the value to string type
head = head.next
return int(S, 2) # python's int() function can easily convert string numbers into other base numbers
2021-1-25 #1290 第一种方法