From 1406bae53aaa3d0d78e319a0e8f590eeb55f8739 Mon Sep 17 00:00:00 2001 From: Bauke Date: Fri, 8 Apr 2022 15:20:57 +0200 Subject: [PATCH] Solve missing-number. --- source/lib.rs | 1 + source/missing_number/mod.rs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 source/missing_number/mod.rs diff --git a/source/lib.rs b/source/lib.rs index 602c50e..d011a51 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -2,6 +2,7 @@ pub mod add_binary; pub mod implement_strstr; pub mod length_of_last_word; pub mod longest_common_prefix; +pub mod missing_number; pub mod palindrome_number; pub mod plus_one; pub mod reverse_integer; diff --git a/source/missing_number/mod.rs b/source/missing_number/mod.rs new file mode 100644 index 0000000..31a32d2 --- /dev/null +++ b/source/missing_number/mod.rs @@ -0,0 +1,18 @@ +pub fn missing_number(numbers: Vec) -> i32 { + // The range of numbers can be described as the total sum of all possible + // numbers in that range. + let total_range = (0..=numbers.len() as i32).sum::(); + + // And since only one number is missing from that range, the difference + // between the range's sum and the numbers' sum will be that missing number. + let sum_of_numbers = numbers.iter().sum::(); + + total_range - sum_of_numbers +} + +#[test] +fn test_missing_number() { + assert_eq!(missing_number(vec![3, 0, 1]), 2); + assert_eq!(missing_number(vec![0, 1]), 2); + assert_eq!(missing_number(vec![9, 6, 4, 2, 3, 5, 7, 0, 1]), 8); +}