LeetCode 1290. Convert Binary Number in a Linked List to Integer 将链表中二进制转换为整数

LeetCode 1290. Convert Binary Number in a Linked List to Integer 将链表中二进制转换为整数

源代码

难度: 简单

题目:

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.

示例1:
在这里插入图片描述

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

示例2:

Input: head = [0]
Output: 0

示例3:

Input: head = [1]
Output: 1

示例4:

Input: head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
Output: 18880

示例5:

Input: head = [0,0]
Output: 0

限制:

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

思路:
这道题目的是将链表中每个结点的值先转化为二进制的形式,然后将其转化为十进制

比较简单的做法(耗费了额外空间):

  1. 链表 -> 数组
  2. 整型数组 - > 字符型数组
  3. 字符型数组 - > 二进制字符串
  4. 二进制字符串 - > 十进制数

代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        arr, str_arr = [], ""
        while head:  # linked list to array
            arr.append(head.val)
            head = head.next
        arr = list(map(str, arr))  # list of int -> list of str
        str_arr = "".join(arr)  # list of str -> str
        return int(str_arr, 2)  # str -> int

测试结果:

Accepted!

Runtime: 24 ms, faster than 88.53% of Python3 online submissions for Convert Binary Number in a Linked List to Integer.

Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Convert Binary Number in a Linked List to Integer.

复杂度分析:

Time Complexity: O(n)

Space Complexity: O(n)

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页