[Bit operation-simple] 1290. Binary linked list to integer (traversal+int()+str()+<<)

[Title]
Give you the head of the reference node of a singly linked list. The value of each node in the linked list is either 0 or 1. It is known that this linked list is a binary representation of an integer number.
Please return the decimal value of the number represented by the linked list.
[Example 1]
Input: head = [1,0,1]
Output: 5
Explanation: Binary number (101) is converted 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: 0
[Prompt] The
linked list is 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.
[Code]
[Python]
Insert picture description here

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        num=0
        while head:
            num=num*2+head.val
            head=head.next
        return num

[Method 2: Traverse+int()]
Insert picture description here

class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        s=""
        while head:
            s+=str(head.val)
            head=head.next
        return int(s,2)

[Method 3: Bit operation] From
Insert picture description here
the perspective of bit operation :
Decimal operation and binary comparison

*  表示为	<<
/  表示为	>>
+  表示为	|
class Solution:
    def getDecimalValue(self, head: ListNode) -> int:
        re = 0
        while head is not None:
            re = (re << 1) | head.val
            head = head.next
        return re

Guess you like

Origin blog.csdn.net/kz_java/article/details/115054064