-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert-binary-number-in-a-linked-list-to-integer.rs
110 lines (101 loc) · 2.67 KB
/
convert-binary-number-in-a-linked-list-to-integer.rs
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
struct Solution;
// Definition for singly-linked list.
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ListNode {
pub val: i32,
pub next: Option<Box<ListNode>>,
}
impl ListNode {
#[allow(unused)]
#[inline]
fn new(val: i32) -> Self {
ListNode { next: None, val }
}
}
impl Solution {
pub fn impl1(head: Option<Box<ListNode>>) -> i32 {
let mut s = String::new();
let mut head = head;
while let Some(node) = head {
s.push_str(&node.val.to_string());
head = node.next;
}
i32::from_str_radix(&s, 2).unwrap_or(0)
}
#[allow(unused)]
pub fn impl2(head: Option<Box<ListNode>>) -> i32 {
let mut head = head;
let mut ans = 0;
while let Some(node) = head {
head = node.next;
ans = node.val + ans * 2;
}
ans
}
pub fn get_decimal_value(head: Option<Box<ListNode>>) -> i32 {
Solution::impl1(head)
}
}
fn main() {
println!("{}", Solution::get_decimal_value(None));
}
#[cfg(test)]
mod tests {
use crate::{ListNode, Solution};
#[test]
fn test_impl1() {
assert_eq!(
Solution::impl1(Some(Box::new(ListNode {
val: 1,
next: Some(Box::new(ListNode {
val: 0,
next: Some(Box::new(ListNode { val: 1, next: None })),
})),
}))),
5
);
assert_eq!(
Solution::impl1(Some(Box::new(ListNode { val: 0, next: None }))),
0
);
assert_eq!(
Solution::impl1(Some(Box::new(ListNode { val: 1, next: None }))),
1
);
assert_eq!(
Solution::impl1(Some(Box::new(ListNode {
val: 0,
next: Some(Box::new(ListNode { val: 0, next: None }))
}))),
0
);
}
#[test]
fn test_impl2() {
assert_eq!(
Solution::impl2(Some(Box::new(ListNode {
val: 1,
next: Some(Box::new(ListNode {
val: 0,
next: Some(Box::new(ListNode { val: 1, next: None })),
})),
}))),
5
);
assert_eq!(
Solution::impl2(Some(Box::new(ListNode { val: 0, next: None }))),
0
);
assert_eq!(
Solution::impl2(Some(Box::new(ListNode { val: 1, next: None }))),
1
);
assert_eq!(
Solution::impl2(Some(Box::new(ListNode {
val: 0,
next: Some(Box::new(ListNode { val: 0, next: None }))
}))),
0
);
}
}