# 二进制链表转整数(1290)

# 题目

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

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

# 示例

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

解释:二进制数 (101) 转化为十进制数 (5)

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

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

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

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

# 提示

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

# 算法

# parseInt()

parseInt(num|string, digit)
1
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
export const getDecimalValue = (head) => {
	let s = "";
	while (head) {
		s += head.val;
		head = head.next;
	}
	return parseInt(s, 2);
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 递归

每次内存函数返回当前的数字total以及位数digit,利用进制转换的公式来求出十进制数字

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
export const getDecimalValue = (head) => {
	function recursion(head, digit, total) {
		if (!head.next) return [head.val ? 1 : 0, 0];
		[total, digit] = recursion(head.next);
		return [head.val ? total + 2 ** (digit + 1) : total, ++digit];
	}
	let [res, digit] = recursion(head, 0, 0);
	return res;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 模拟

根据进制转换的算法,从高位开始模拟转换:num = num * 2 + head.val

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
export const getDecimalValue = (head) => {
	let num = 0;
	while (head) {
		num = num * 2 + head.val;
		head = head.next;
	}
	return num;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15