Open Tcdian opened 3 years ago
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function getDecimalValue(head: ListNode | null): number {
let result = 0;
let digits = 0;
let patrol = head;
while (patrol !== null) {
digits++;
patrol = patrol.next;
}
patrol = head;
while (patrol !== null) {
result += patrol.val * Math.pow(2, --digits);
patrol = patrol.next;
}
return result;
};
1290. Convert Binary Number in a Linked List to Integer
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.
Example 1
Example 3
Example 4
Example 5
Constraints
30
.0
or1
.