美文网首页
LeetCode 1290. Convert Binary Nu

LeetCode 1290. Convert Binary Nu

作者: LiNGYu_NiverSe | 来源:发表于2020-12-04 23:34 被阅读0次

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.
给定头节点,它是单链接列表的参考节点。链表中每个节点的值为0或1。链表中包含数字的二进制表示形式。

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

Constraints:

  • The Linked List is not empty.
  • Number of nodes will not exceed 30.
  • Each node's value is either 0 or 1.

Solution:

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        vals = []
        i = head
        while i:
            vals.append(i.val)
            i = i.next
        str_val = "".join(map(str, vals))
        return int(str_val, base = 2)

The idea is to traverse this linked list and get the value of each node, then we change it to str so that we can concatenate it to a string number and then use int to convert it to 10-based int.
解法是遍历此链表,并获取每个节点的值,然后将其更改为str,以便可以将其连接为字符串号,然后使用int将其转换为基于10的int。

相关文章

网友评论

      本文标题:LeetCode 1290. Convert Binary Nu

      本文链接:https://www.haomeiwen.com/subject/wmswwktx.html