Leetcode1290: Convert Binary Number in a Linked List to Integer (Python)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


题目描述

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:
1290
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10

题目分析

这是一题关于单链表的题目,每个单链表都有一个头指针 Head 作为开端,然后指向下一个节点 Node,而每一个节点都由一个 Next 指针指向下一个节点。

链表(linked list)和数组(array)的好处在于:
  1. 插入和删除的复杂度低
  1. 对于不知道有多少个节点的情况,每有一个新的元素就链接到链表里来

这题的思路比较简单,遍历整个链表把每一个二进制的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 第一种方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值