1411 Convert Binary Number In A Linked List To Integer
1411 Convert Binary Number In A Linked List To Integer
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.
The most significant bit is at the head of the linked list.
Example 1:
1
2
3
4
5
**Input:** head = [1,0,1]
**Output:** 5
**Explanation:** (101) in base 2 = (5) in base 10
Example 2:
1
2
3
4
**Input:** head = [0]
**Output:** 0
Constraints:
1
2
3
The Linked List is not empty.
Number of nodes will not exceed 30.
Each node's value is either 0 or 1.
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
32
33
// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
// pub val: i32,
// pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
// #[inline]
// fn new(val: i32) -> Self {
// ListNode {
// next: None,
// val
// }
// }
// }
use std::ptr::null;
impl Solution {
pub fn get_decimal_value(mut head: Option<Box<ListNode>>) -> i32 {
let mut res = 0;
while let Some(node) = head {
res = (res << 1) | node.val;
head = node.next;
}
res
}
}
This post is licensed under CC BY 4.0 by the author.
