File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # [ 1290. 二进制链表转整数] ( https://leetcode.cn/problems/convert-binary-number-in-a-linked-list-to-integer/description/ )
2+
3+ > ** 日期** :2025-07-14
4+ > ** 所用时间** :10min
5+
6+ ## 1. 遍历链表
7+
8+ ### 题目分析
9+
10+ 本题给定一个单链表,链表的每个节点的值为 0 或 1,表示一个二进制数的各位(最高位在链表头部)。要求将该二进制数转换为十进制整数。
11+
12+ 例如:链表 1 -> 0 -> 1 表示二进制 101,对应十进制 5。
13+
14+ ### 解题思路
15+
16+ 我们可以遍历链表,每次遇到一个新节点时,将当前结果左移一位(相当于乘以 2),再加上当前节点的值。这样遍历到链表末尾时,得到的就是对应的十进制数。
17+
18+ #### 步骤详解
19+
20+ 1 . 初始化结果变量 ` ans = 0 ` 。
21+ 2 . 从头遍历链表,对于每个节点:
22+ - 先将 ` ans ` 左移一位(` ans <<= 1 ` ),为当前位腾出空间。
23+ - 再加上当前节点的值(` ans += head.val ` )。
24+ 3 . 遍历结束后,` ans ` 即为所求。
25+
26+ #### 复杂度分析
27+
28+ - 时间复杂度:$O(n)$,其中 $n$ 为链表长度,需要遍历每个节点一次。
29+ - 空间复杂度:$O(1)$,只用常数级变量。
30+
31+ ** Python3**
32+
33+ ``` python
34+ class Solution :
35+ def getDecimalValue (self , head : Optional[ListNode]) -> int :
36+ ans = 0
37+ while head:
38+ ans <<= 1
39+ ans += head.val
40+ head = head.next
41+ return ans
42+ ```
You can’t perform that action at this time.
0 commit comments