-
Description Correction pour agir comme la question originale decrit.
Code fn closest_to_zero(ints: &[i32]) -> i32 { *ints.iter().min_by_key(|x| (x.abs(), x.is_negative())).unwrap_or(&0) }
Test Cases mod tests { use super::*; fn test_simple() { assert_eq!(closest_to_zero(&[7, 5, 9, 1, 4]), 1); } fn test_negative() { assert_eq!(closest_to_zero(&[7, -4, -3, -12, 5, 9, -2, 4]), -2); } fn test_same() { assert_eq!(closest_to_zero(&[-5, -5]), -5); } fn test_empty() { assert_eq!(closest_to_zero(&[]), 0); } fn test_with_zero() { assert_eq!(closest_to_zero(&[-5, 0, 1, 5]), 0); } fn test_same_distance() { assert_eq!(closest_to_zero(&[-5, -1, 1, 5]), 1); } }
Output:
-
Code - fn closest_to_zero(ints: &[i32]) -> i32 {
*ints.iter().min_by_key(|x| x.abs()).unwrap_or(&0)- *ints.iter().min_by_key(|x| (x.abs(), x.is_negative())).unwrap_or(&0)
- }
Test Cases - #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_simple() {
- assert_eq!(closest_to_zero(&[7, 5, 9, 1, 4]), 1);
- }
- #[test]
- fn test_negative() {
- assert_eq!(closest_to_zero(&[7, -4, -3, -12, 5, 9, -2, 4]), -2);
- }
- #[test]
- fn test_same() {
- assert_eq!(closest_to_zero(&[-5, -5]), -5);
- }
- #[test]
- fn test_empty() {
- assert_eq!(closest_to_zero(&[]), 0);
- }
- #[test]
- fn test_with_zero() {
- assert_eq!(closest_to_zero(&[-5, 0, 1, 5]), 0);
- }
- #[test]
- fn test_same_distance() {
assert_eq!(closest_to_zero(&[-5, -1, 1, 5]), -1);- assert_eq!(closest_to_zero(&[-5, -1, 1, 5]), 1);
- }
- }
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}