The title
Give you a single linked list reference node head. The value of each node in the linked list is either 0 or 1. This list is known to be a binary representation of an integer number.
Return the decimal value of the number represented by the list.
Example 1: Input: head = [1,0,1] Output: 5 Description: Convert binary number (101) to decimal number (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: 0Copy the code
Tip:
Linked lists are not empty. The total number of nodes in the linked list does not exceed 30. The value of each node is either 0 or 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 # print(resStr) return int(resStr, 2) If __name__ == '__main__': # # # #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)Copy the code