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
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
# 링크드리스트의 값들을 빈리스트를 만들어 추가시켜주었다.
linked = []
while head is not None:
linked.append(head.val)
head = head.next
linked = linked[::-1]
# for문을 돌면서 비트연산을 하였다.
result = 0
for i in range(len(linked)):
num = pow(2, i) * linked[i]
result += num
return result
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
result = 0
while head:
result <<= 1
result |= head.val
head = head.next
return result
<<
or >>
(해당 방향쪽으로 변수의 값을 지정된 비트 수만큼 이동하는 연산자)a = 3
print('binary = ', bin(a), 'decimal = ', a)
a <<= 3
print('binary = ', bin(a), 'decimal = ', a)
a |= 2
print('binary = ', bin(a), 'decimal = ', a)
#binary = 0b11 decimal = 3
#binary = 0b11000 decimal = 24
#binary = 0b11010 decimal = 26
3 << 3 = a * 2^3