Problem
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.
Solution
pub fn reverse_list(node: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut s = node; let mut e = None; while let Some(mut n) = s.take() { s = n.next; n.next = e; e = Some(n); } e } impl Solution { pub fn add_two_numbers(l1: Option<Box<ListNode>>, l2: Option<Box<ListNode>>) -> Option<Box<ListNode>> { let mut l1_curr = l1; let mut l2_curr = l2; let mut carry = 0; let mut result = None; while l1_curr.is_some() || l2_curr.is_some() || carry > 0{ let mut sum = carry; if let Some(n) = l1_curr { sum += n.val; l1_curr = n.next; } if let Some(n) = l2_curr { sum += n.val; l2_curr = n.next; } carry = sum/10; let mut node = ListNode::new(sum%10); node.next = result; result = Some(Box::new(node)); } reverse_list(result) } }
© 著作权归作者所有
举报
相关热门文章
发表评论
0/200