diff --git a/source/lib.rs b/source/lib.rs index f87d131..406452b 100644 --- a/source/lib.rs +++ b/source/lib.rs @@ -18,6 +18,7 @@ pub mod roman_to_integer; pub mod set_mismatch; pub mod two_sum; pub mod valid_anagram; +pub mod valid_number; pub mod valid_palindrome; pub mod valid_parenthesis; pub mod word_pattern; diff --git a/source/valid_number/mod.rs b/source/valid_number/mod.rs new file mode 100644 index 0000000..8351df6 --- /dev/null +++ b/source/valid_number/mod.rs @@ -0,0 +1,23 @@ +pub fn is_number(string: String) -> bool { + let string = string.to_lowercase(); + + if string.contains("inf") || string.contains("nan") { + return false; + } + + let mut parts = string.split("e"); + + let valid_significand = match parts.next() { + Some(part) => part.parse::().is_ok(), + None => unreachable!(), + }; + + let valid_exponent = match parts.next() { + Some(part) => part.parse::().is_ok(), + None => true, + }; + + let nothing_remaining = parts.next().is_none(); + + valid_significand && valid_exponent && nothing_remaining +} diff --git a/tests/valid_number.rs b/tests/valid_number.rs new file mode 100644 index 0000000..0dce8ac --- /dev/null +++ b/tests/valid_number.rs @@ -0,0 +1,13 @@ +use leetcode::valid_number::is_number; + +use test_case::test_case; + +#[test_case("0", true; "example 1")] +#[test_case("e", false; "example 2")] +#[test_case(".", false; "example 3")] +#[test_case("-inf", false; "infinity")] +#[test_case("NaN", false; "not a number")] +#[test_case("", false; "empty")] +fn test_valid_number(input: &str, expected: bool) { + assert_eq!(is_number(input.to_string()), expected); +}