スポンサーリンク

【LeetCode】1290. Convert Binary Number in a Linked List to Integer 解答・解説【Python】

スポンサーリンク
スポンサーリンク
この記事は約3分で読めます。

 

問題

原文

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.

The most significant bit is at the head of the linked list.

 

Example 1:

Example 2:

 

Constraints:

  • The Linked List is not empty.
  • Number of nodes will not exceed 30.
  • Each node’s value is either 0 or 1.

 

内容

単方向連結リストheadが与えられます。各ノードの値は0,1で、バイナリ値のみです。

連結リストを10進数の値にして返してください。

最上位bitは連結リストの先頭です。

 

※正しくない可能性があります。

方針

・各要素を文字列にしたリストに変換後、連結してから10進数に変換

解答

解答1:

”.join(list_int)でリスト内の各要素を結合することができる

例:[“1″,”2″,”3”]であれば123になる

リスト内の各要素は文字列である必要があるため、list_intに保持するときにstr()で文字列に変換した。

 

解答2

こっちはよくわからないので、コメントをここにメモ

ビットシフト・ビット演算をしている?

For those of you who don’t understand how the algorithm works, it is easier to visualize as it is done in binary.

Take For Example:
1101 -> 13

Binary View

0000 * 2 # shift left
0000 + 1 # add bit

0001 * 2 # shift left
0010 + 1 # add bit

0011 * 2 # shift left
0110 + 0 # add bit

0110 * 2 # shift left
1100 + 1 # add bit

1101 # 13

Decimal View

0 * 2 # x2
0 + 1 # add bit

1 * 2 # x2
2 + 1 # add bit

3 * 2 # x2
6 + 0 # add bit

6 * 2 # x2
12 + 1 # add bit

13 # Answer

 

補足・参考・感想

参考

 

 

前:876. Middle of the Linked List

次:1232. Check If It Is a Straight Line

LeetCode 解答・解説記事一覧

コメント