0002.两数相加
方法一:模拟加法
时间复杂度 $O(n)$,空间复杂度 $O(1)$。
impl Solution {
pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
let mut ans = ListNode::new(-1);
let (mut l1, mut l2) = (l1, l2);
let mut remainder = 0;
let mut p = &mut ans;
while l1.is_some() || l2.is_some() || remainder != 0 {
if let Some(a) = l1 {
l1 = a.next;
remainder += a.val;
}
if let Some(b) = l2 {
l2 = b.next;
remainder += b.val;
}
p.next = Some(Box::new(ListNode::new(remainder % 10)));
p = p.next.as_mut().unwrap().as_mut();
remainder /= 10;
}
ans.next
}
}