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.

Input: head = [1,0,1]
Output: 5
Explanation: (101) in base 2 = (5) in base 10
把链表对应的二进制数转为十进制数,链表的head对应二进制数的最高位。
思路:
可能会想到用一个数组把数字都保存下来,然后从低位开始转换。但是这样space 和 time complexity都很高。
可以用二进制位运算解决,定义一个变量result。
从head读起,每往右读一位,result左移一位,同时与当前head.val取或,这相当于result*2 + head.val,直到head == null
public int getDecimalValue(ListNode head) {
if(head == null) {
return 0;
}
int result = 0;
while(head != null) {
result = result << 1 | head.val;
head = head.next;
}
return result;
}
本文介绍了一种高效的算法,用于将给定的二进制链表转换为十进制数,避免了数组存储和高复杂度。通过位运算实现,展示了如何利用链表节点逐位相加,最终返回链表所代表的十进制数值。
1919

被折叠的 条评论
为什么被折叠?



