1290.二进制链表转整数:链表+进制转换

【LetMeFly】1290.二进制链表转整数:链表+进制转换

力扣题目链接:https://leetcode.cn/problems/convert-binary-number-in-a-linked-list-to-integer/

给你一个单链表的引用结点 head。链表中每个结点的值不是 0 就是 1。已知此链表是一个整数数字的二进制表示形式。

请你返回该链表所表示数字的 十进制值

 

示例 1:

输入:head = [1,0,1]
输出:5
解释:二进制数 (101) 转化为十进制数 (5)

示例 2:

输入:head = [0]
输出:0

示例 3:

输入:head = [1]
输出:1

示例 4:

输入:head = [1,0,0,1,0,0,1,1,1,0,0,0,0,0,0]
输出:18880

示例 5:

输入:head = [0,0]
输出:0

 

提示:

  • 链表不为空。
  • 链表的结点总数不超过 30
  • 每个结点的值不是 0 就是 1

解题方法:进制转换

二进制如何转为十进制?

初始值$ans = 0$,遍历二进制数字,并令$ans\times 2+当前二进制位$

  • 时间复杂度$O(len(list))$
  • 空间复杂度$O(1)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
* @Author: LetMeFly
* @Date: 2025-07-14 23:37:54
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-07-14 23:42:31
*/
#if defined(_WIN32) || defined(__APPLE__)
#include "_[1,2]toVector.h"
#endif

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
int getDecimalValue(ListNode* head) {
int ans = 0;
while (head) {
ans = ans * 2 + head->val;
head = head->next;
}
return ans;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
'''
Author: LetMeFly
Date: 2025-07-14 23:37:54
LastEditors: LetMeFly.xyz
LastEditTime: 2025-07-14 23:43:59
'''
from typing import Optional

# # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

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

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/*
* @Author: LetMeFly
* @Date: 2025-07-14 23:37:54
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-07-14 23:45:19
*/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int getDecimalValue(ListNode head) {
int ans = 0;
while (head != null) {
ans = ans * 2 + head.val;
head = head.next;
}
return ans;
}
}

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
* @Author: LetMeFly
* @Date: 2025-07-14 23:37:54
* @LastEditors: LetMeFly.xyz
* @LastEditTime: 2025-07-14 23:47:42
*/
package main

/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getDecimalValue(head *ListNode) (ans int) {
for ; head != nil; head = head.Next {
ans = ans * 2 + head.Val
}
return
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源


1290.二进制链表转整数:链表+进制转换
https://blog.letmefly.xyz/2025/07/14/LeetCode 1290.二进制链表转整数/
作者
发布于
2025年7月14日
许可协议