1
Fork 0

Solve missing-number.

This commit is contained in:
Bauke 2022-04-08 15:20:57 +02:00
parent 84ceb51cb1
commit 1406bae53a
Signed by: Bauke
GPG Key ID: C1C0F29952BCF558
2 changed files with 19 additions and 0 deletions

View File

@ -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;

View File

@ -0,0 +1,18 @@
pub fn missing_number(numbers: Vec<i32>) -> 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::<i32>();
// 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::<i32>();
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);
}