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.
給定頭節(jié)點素邪,它是單鏈接列表的參考節(jié)點。鏈表中每個節(jié)點的值為0或1。鏈表中包含數(shù)字的二進(jìn)制表示形式炫彩。
Return the decimal value of the number in the linked list.
返回鏈接列表中數(shù)字的十進(jìn)制值宠默。
Example 1:
Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
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
Constraints:
- The Linked List is not empty.
- Number of nodes will not exceed
30
. - Each node's value is either
0
or1
.
Solution:
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
vals = []
i = head
while i:
vals.append(i.val)
i = i.next
str_val = "".join(map(str, vals))
return int(str_val, base = 2)
The idea is to traverse this linked list and get the value of each node, then we change it to str so that we can concatenate it to a string number and then use int to convert it to 10-based int.
解法是遍歷此鏈表嘉抓,并獲取每個節(jié)點的值始绍,然后將其更改為str访锻,以便可以將其連接為字符串號拔恰,然后使用int將其轉(zhuǎn)換為基于10的int因谎。