当前位置:网站首页>LeetCode 1290. Binary linked list to integer

LeetCode 1290. Binary linked list to integer

2022-06-24 04:51:00 freesan44

subject

Give you a single chain table reference node  head. The value of each node in the list is not 0 Namely 1. It is known that this list is a binary representation of an integer number .

Please go back to the Decimal value .

image.png
 Example  1:



 Input :head = [1,0,1]
 Output :5
 explain : Binary number  (101)  Convert to decimal  (5)
 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

Tips :

Link list is not empty .

The total number of nodes in the list does not exceed  30.

The value of each node is not  0 Namely 1.

Their thinking

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        resStr = ""
        while head != None:
            resStr += str(head.val)
            head = head.next
        # Binary to decimal  int( Binary value ,2)
        # print(resStr)
        return int(resStr, 2)

if __name__ == '__main__':
    # # Sample linked list , Pay attention to copying !
    # #L1 1->2->3->4->5
    # l1 = ListNode(1,ListNode(2, ListNode(3, ListNode(4, ListNode(5)))))
    # #L2 1->3->4
    # l2 = ListNode(1, ListNode(3, ListNode(4)))

    # list1 = [1, 2, 3, 3, 2, 1]
    # list1 = [1, 0, 1]
    list1 = [1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]
    nodeL1 = ListNode()
    headL1 = nodeL1
    while len(list1) >0:
        node = ListNode(list1.pop(0))
        nodeL1.next = node
        nodeL1 = node
    headL1 = headL1.next
    tempHeadL1 = headL1
    while(tempHeadL1.next != None):
        # print(tempHeadL1.val)
        tempHeadL1 = tempHeadL1.next

    ret = Solution().getDecimalValue(headL1)
    print(ret)
原网站

版权声明
本文为[freesan44]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/09/20210903184937262u.html