forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths0002_add_two_numbers.rs
98 lines (90 loc) · 2.78 KB
/
s0002_add_two_numbers.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
/**
* [2] Add Two Numbers
*
* You are given two non-empty linked lists representing two non-negative
* integers. The digits are stored in reverse order and each of their nodes
* contain a single digit. Add the two numbers and return it as a linked list.
*
* You may assume the two numbers do not contain any leading zero, except the
* number 0 itself.
*
* Example:
*
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
* Explanation: 342 + 465 = 807.
*
*/
pub struct Solution {}
use crate::util::linked_list::{to_list, ListNode};
// problem: https://leetcode.com/problems/add-two-numbers/
// discuss: https://leetcode.com/problems/add-two-numbers/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn add_two_numbers(
l1: Option<Box<ListNode>>,
l2: Option<Box<ListNode>>,
) -> Option<Box<ListNode>> {
let (mut l1, mut l2) = (l1, l2);
let mut dummy_head = Some(Box::new(ListNode::new(0)));
let mut tail = &mut dummy_head;
let (mut l1_end, mut l2_end, mut overflow) = (false, false, false);
loop {
let lhs = match l1 {
Some(node) => {
l1 = node.next;
node.val
}
None => {
l1_end = true;
0
}
};
let rhs = match l2 {
Some(node) => {
l2 = node.next;
node.val
}
None => {
l2_end = true;
0
}
};
// if l1, l2 end and there is not overflow from previous operation, return the result
if l1_end && l2_end && !overflow {
break dummy_head.unwrap().next;
}
let sum = lhs + rhs + if overflow { 1 } else { 0 };
let sum = if sum >= 10 {
overflow = true;
sum - 10
} else {
overflow = false;
sum
};
tail.as_mut().unwrap().next = Some(Box::new(ListNode::new(sum)));
tail = &mut tail.as_mut().unwrap().next
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2() {
assert_eq!(
Solution::add_two_numbers(to_list(vec![2, 4, 3]), to_list(vec![5, 6, 4])),
to_list(vec![7, 0, 8])
);
assert_eq!(
Solution::add_two_numbers(to_list(vec![9, 9, 9, 9]), to_list(vec![9, 9, 9, 9, 9, 9])),
to_list(vec![8, 9, 9, 9, 0, 0, 1])
);
assert_eq!(
Solution::add_two_numbers(to_list(vec![0]), to_list(vec![0])),
to_list(vec![0])
)
}
}